我正在开发一个基于 YII 模块的应用程序
需要限制用户的某些操作以及整个模块
我能够在规则中使用'表达式'+回调
来限制用户,但现在我想对两个不同的操作使用相同的回调函数,即我有一个我想要获得的回调函数参数值并根据该值评估要执行的操作,这是我迄今为止所做的
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index'),
'users'=>array('*'),
'expression'=>array($this, "checkAccessRule"),
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('login'),
'users'=>array('?'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('view','create','update','admin','delete'),
'users'=>array('@'),
'expression'=>array($this, "checkAccessRule"),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
回调函数
function checkAccessRule($op){
if($op == 1){
if(in_array($this->module->getName(), Yii::app()->user->getState("companyModules")))
return true;
return false;
}elseif($op == 2){
if((Yii::app()->user->getState("user_role") == 1) && (in_array($this->module->getName(), Yii::app()->user->getState("companyModules"))))
return true;
return false;
}
}
如果我发送此“$op”,则无法从回调中获取它 'expression'=>array($this, "checkAccessRule(1)"),
如有任何帮助,我们将不胜感激
最佳答案
这是行不通的,当你声明函数名称时,它将通过 Yii 作为字符串调用,因此 (1)
将被视为函数名称的一部分。幸运的是,表达式参数也接受匿名函数 (function(){}
)。所以:
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index'),
'users'=>array('*'),
'expression'=>function(){$this->checkAccessRule(1)},
),
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('login'),
'users'=>array('?'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('view','create','update','admin','delete'),
'users'=>array('@'),
'expression'=>function(){$this->checkAccessRule(1)},,
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
应该可以。
关于Yii AccessRules 将参数传递给表达式中的回调函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10192720/