我查看了Yii中rbac的文档,并认为我理解它是如何工作的,直到我实际尝试它。
这是检查帖子的作者是否正在尝试获取操作授权的规则:
class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
* @param string|integer $user the user ID.
* @param Item $item the role or permission that this rule is associated with
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return boolean a value indicating whether the rule permits the role or permission it is associated with.
*/
public function execute($user, $item, $params)
{
return isset($params['model']) ? $params['model']->createdBy == $user : false;
}
}
这就是我试图使用规则和Yii的rbac:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if (\Yii::$app->user->can('update', ['model' => $model])) {
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
}
但是,当我尝试编辑帖子时,我得到了这个:
Getting unknown property: app\models\Post::createdBy
所以我认为我必须用userId替换createdBy,这是表Post中的一列,我得到一个空白页,这意味着它不起作用。所以我想猜猜$ user是什么。
我也尝试过:
return isset($params['model']) ? $params['model']->userId == $user->id : false;
我得到了:Trying to get property of non-object.
我该怎么做才能让它发挥作用? doc似乎建议你只需要在控制器动作中插入条件以使其工作,但似乎根本不是这样。
var dump:
object(app\models\Post)[75]
private '_attributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'userId' => int 1
'title' => string 'test' (length=4)
'content' => string 'lol' (length=3)
'dateCreated' => null
'dateUpdated' => null
private '_oldAttributes' (yii\db\BaseActiveRecord) =>
array (size=6)
'id' => int 1
'userId' => int 1
'title' => string 'test' (length=4)
'content' => string 'lol' (length=3)
'dateCreated' => null
'dateUpdated' => null
private '_related' (yii\db\BaseActiveRecord) =>
array (size=0)
empty
private '_errors' (yii\base\Model) => null
private '_validators' (yii\base\Model) => null
private '_scenario' (yii\base\Model) => string 'default' (length=7)
private '_events' (yii\base\Component) =>
array (size=0)
empty
private '_behaviors' (yii\base\Component) =>
array (size=0)
empty
null
答案 0 :(得分:1)
第一个错误表示您的createdBy
模型中没有Post
属性。你呢?
第二个错误是关于尝试获取非对象变量的属性。你能在返回前显示var_dump($params['model']); var_dump($user);
吗?