文件 frontend/libs/FilterTest.phpphp
<?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.phpweb
<?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處理 } }