yii2 拦截器
在控制器中可以自定义对action的拦截器,拦截器需要继承 yiiaseActionFilter
参考代码:
class BaseUserAuthorizeFilter extends ActionFilter { public $rules = []; public $actions = []; /** * @param yiiaseAction $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' => ['@'], ], ], ], ]; }