Yii AccessRules将参数传递给表达式中的回调函数

时间:2012-04-17 13:59:54

标签: yii yii-components

我正在开发基于YII模块的应用程序

需要限制用户执行某些操作以及整个模块

我能够在规则中使用'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)"),

无法从回调中获得此'$ op'

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:1)

这不起作用,当你声明函数名称时,它将通过Yii作为字符串调用,因此(1)将被视为函数名称的一部分。幸运的是,expression参数也接受匿名函数(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('*'),

        ),
    );
}

应该工作。