我关注this guide,但我无权更新自己的帖子。 我创建了AuthorRule.php
<?php
namespace common\rbac;
use yii\rbac\Rule;
use backend\controllers\PostsController;
class AuthorRule extends Rule
{
public $name = 'isAuthor';
/**
* @param string|int $user the user ID.
* @param Item $item the role or permission that this rule is associated width.
* @param array $params parameters passed to ManagerInterface::checkAccess().
* @return bool 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;
}
}
和PostsController.php
use common\rbac\AuthorRule;
public function actionUpdate($id)
{
if (\Yii::$app->user->can('updateOwnPost', ['model' => $model]))
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->post_id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
else
{
throw new NotFoundHttpException('You have no access to update this post');
}
}