2012-04-17 117 views
2

我正在开发基于Yii的AccessRules传递参数给回调函数的表达式

需要限制某些操作的用户以及整个模块上谊模块的应用

我能使用限制用户'expression' + callback在规则中,但现在我想为两个不同的动作使用相同的回调函数,即我有一个回调函数,我想要获取参数值并根据该值评估执行什么动作,这里是我已经完成的工作

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; 
     } 
    } 

不能,如果我把它'expression'=>array($this, "checkAccessRule(1)"),

任何帮助,将不胜感激

回答

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('*'), 

     ), 
    ); 
} 

应该工作。

+0

谢谢,它有点改变:) – Junaid 2012-04-18 13:17:46