How to pass arguments to access rules expressions in yii framework controller
ow to pass arguments to accessRules experessions The code below doesn't work becouse $owner_id is not defined in class where expression is evaluated. Any ideas how to fix it?
public function accessRules(){
$owner_id = $this->loadModel()->owner_id;
return array(
...
array('allow',
'actions'=>array('upd开发者_开发问答ate'),
'expression'=>'$user->id==$owner_id',
));
}
It's very hard to tell what you're trying to do or what the problem is, but I would use "{}" and double quotes rather than single quotes when building your array so that your variables are interpreted correctly:
public function accessRules(){
$owner_id = $this->loadModel()->owner_id;
return array(
...
array('allow',
'actions'=>array('update'),
'expression'=>"{$user->id}=={$owner_id}",
));
}
You can use
array('allow',
'actions'=>array('update'),
'users'=>array(Yii::app()->user->name),
'expression' => '(Yii::app()->user->id == ($_GET[\'id\']))',
),
function isPostOwner() {
$post = Post::model()->findByPk($_GET['post_id']);
$owner_id = $post->owner_id;
if(Yii::app()->user->id === $owner_id)
return true;
return false;
}
in this code in FindBYPK function $_GET['post_id'] this value from where in will get
You can create a function in the current controller and call it in the expression itself.
An example with a blog post:
Put this function in the current controller where your access rules are.
function isPostOwner() {
$post = Post::model()->findByPk($_GET['post_id']);
$owner_id = $post->owner_id;
if(Yii::app()->user->id === $owner_id)
return true;
return false;
}
And in the accessRules section, you do this:
public function accessRules(){
return array(
...
array('allow',
'actions'=>array('update'),
'expression'=>"Yii::app()->controller->isPostOwner()",
));
}
Hope that helps.
Since PHP 5.3 one can use an anonymous functions instead of code in a string
...
'expression' => function ($user) {
return $user->... == ...;
},
...
精彩评论