YII behaviors使用
文件 frontend/libs/FilterTest.php
<?php /** * Created by PhpStorm. * Date: 2016/5/27 * Time: 14:16 */ namespace frontend\libs; use Yii; use yii\base\Action; use yii\base\ActionFilter; class FilterTest extends ActionFilter{ //在action之前运行,可用来过滤输入 public function beforeAction($action) { echo '在调用action前显示<br/>'; return TRUE;//如果返回值为false,则action不会运行 } //在action之后运行,可用来过滤输出 public function afterAction($action, $result) { return $result.'在调用action后显示<br/>';//可以对action输出的$result进行过滤,retun的内容会直接显示 } }
frontend/controllers/TestbehaviorController.php
<?php /** * Created by PhpStorm. * Date: 2016/5/27 * Time: 14:19 */ namespace frontend\controllers; use yii\web\controller; class TestbehaviorController extends Controller{ public function behaviors(){ return [ 'test'=>[ 'class'=>'frontend\libs\FilterTest',//调用过滤器 ], ]; } public function actionFilter(){ return "当前action显示<br/>";//返回的内容会递交给过滤器,由afterAction处理 } }