yii2:如何为访问行为添加多个规则

时间:2017-10-11 08:27:02

标签: php yii2

我想在一种行为中使用多规则。

我该如何解决这个问题?

   public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'rules' => [
                    [
                    'actions' => ['file'],
                    'allow' => true,
                    'roles' => ['user2'],
                ],
                    [
                    'actions' => ['file'],
                    'allow' => false,
                    'roles' => ['document'],
                ],
            ],

1 个答案:

答案 0 :(得分:0)

这个问题对我来说不是很清楚,但我认为你想做这样的事情......

扩展AccesRule类并实现角色的访问方式

class AccessRule extends \yii\filters\AccessRule {
protected function matchRole($user)
    {
        if (empty($this->roles)) {
            return true;  // no roles defined = access ok
        }
        foreach ($this->roles as $role) {
            // return true if role is allowed based on $user (define your logic)
        }
        return false; // no match, ie no access
    }
}

然后将这个新规则类添加到AccessControl ...

'access' => [
    'class' => \yii\filters\AccessControl::className(),
    'ruleConfig' => ['class' => '\my\namespace\AccessRule'],
    'rules' => [
        ...
    ],
]

注意:代码未经过测试。