【问题标题】:Yii AccessRules Pass Parameter to Callback function in expressionYii AccessRules 将参数传递给表达式中的回调函数
【发布时间】:2012-04-17 13:59:53
【问题描述】:

我正在开发一个基于 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”

任何帮助将不胜感激

【问题讨论】:

    标签: yii yii-components


    【解决方案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('*'),
    
            ),
        );
    }
    

    应该可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-14
      • 2011-03-28
      • 2011-10-05
      相关资源
      最近更新 更多