How to pass arguments to access rules expressions in yii framework controller

StackOverflow https://stackoverflow.com/questions/3005708

  •  25-09-2019
  •  | 
  •  

문제

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('update'),
                '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->... == ...;
},
...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top