一:一个controller的拦截器
关于yii拦截器的实现,首先说明本文的拦截器的例子是在controller中使用的,拦截器会在controller中的function behavior函数中指明使用哪个拦截器,behavior函数如下定义
public function behaviors()
{
return [
[
'class'=>TestFilter::className(),
'only'=>['index'],
]
];
}
controller控制器默认是对所有action有效的,但是可以通过指定only,只对某些特定的动作起效,也可以通过指定except除了部分动作,其他起效,
而过滤器的定义是这样的
这里需要注意的是在beforeAction中返回值一定要是true才会继续执行action!!!namespace yii\filters; use yii\base\ActionFilter; class TestFilter extends ActionFilter { public function beforeAction($action) { echo "this is test beforeAction"; return true; } public function afterAction($action, $result) { var_dump($result); echo "this is test afterAction"; } }
而action的返回值会被afterAction的第二个参数$result接受!!!
二: 一个应用的拦截器:
这只是针对一个controller的拦截器,还可以设置一个针对一个应用的拦截器设置,其设置所在地是在component.php
public function behaviors()
{
return [['class'=>'yii\filters\testfilter']];
}