yii2 [行为] behaviors 拦截器

yii2 拦截器

 

    在控制器中可以自定义对action的拦截器,拦截器需要继承 \yii\base\ActionFilter

   参考代码:

      

class BaseUserAuthorizeFilter extends ActionFilter
{
    public $rules = [];
    public $actions = [];

    /**
     * @param \yii\base\Action $action
     * @return bool
     */
    public function  beforeAction($action)
    {
        .....
        return true;
    }

    public function afterAction($action, $result)
    {
        
        return $result;
    }



}

控制器配置拦截器:

     其中 UserAuthorizeFilter 为自定义拦截器 。

  关键配置:

       only :仅对数组中action对应的请求地址有效

       except:排除掉数组中action对应的请求地址有效

 public function behaviors()
    {
        return [
            'access' => [
                'class' => UserAuthorizeFilter::className(),
               // 'only' => ['index'],
               // 'except' => ['getlist'],
                'rules' => [
                    [
                        'actions' => ['error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

 

      

posted @ 2015-06-17 17:19  Rhythmk  阅读(4474)  评论(0编辑  收藏  举报
Rhythmk 个人笔记