2012-04-17 112 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