Yii中特殊行為ActionFilter的使用方法示例
新建 app\filters\LoggingFilter 繼承 yii\base\ActionFilter
LoggingFilter 的功能: 在指定請(qǐng)求的 action 前后各記錄一條日志
<?php namespace app\filters; use yii\base\ActionFilter; class LoggingFilter extends ActionFilter { public function beforeAction($action) { parent::beforeAction($action); // To do something printf('This is a logging for %s\beforeAction.%s', $this->getActionId($action), PHP_EOL); return true; } public function afterAction($action, $result) { parent::afterAction($action, $result); // To do something printf('This is a logging for %s\afterAction.%s', $this->getActionId($action), PHP_EOL); return true; } }
新建 app\controllers\SystemController
<?php namespace app\controllers; use app\filters\LoggingFilter; class SystemController extends \yii\web\Controller { public function behaviors() { parent::behaviors(); return [ 'anchorAuth' => [ 'class' => LoggingFilter::className(), 'only' => ['test', 'test-one'], // 僅對(duì) 'test'、'test-one' 生效 'except' => ['test-one'], // 排除 'test-one' ], ]; } public function actionTestOne() { printf('This is a testing for %s.%s', $this->getRoute(), PHP_EOL); } public function actionTestTwo() { printf('This is a testing for %s.%s', $this->getRoute(), PHP_EOL); } public function actionTest() { printf('This is a testing for %s.%s', $this->getRoute(), PHP_EOL); } }
測(cè)試
請(qǐng)求 http://yii.test/index.php?r=system/test
This is a logging for test\beforeAction. This is a testing for system/test. This is a logging for test\afterAction.
請(qǐng)求 http://yii.test/index.php?r=system/test-one
This is a testing for system/test-one.
請(qǐng)求 http://yii.test/index.php?r=system/test-two
This is a testing for system/test-two.
總結(jié)
Yii 中的 ActionFilter(過(guò)濾器)相當(dāng)于 Laravel 中的 Middleware(中間件),beforeAction 相當(dāng)于前置中間件,afterAction 相當(dāng)于后置中間件。
到此這篇關(guān)于Yii中特殊行為ActionFilter使用的文章就介紹到這了,更多相關(guān)Yii特殊行為ActionFilter使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
windows環(huán)境下使用Composer安裝ThinkPHP5
本文給大家分享的是在windows環(huán)境下使用Composer安裝ThinkPHP5的具體步驟和方法,非常的簡(jiǎn)單實(shí)用,有需要的小伙伴可以參考下2018-05-05PHP函數(shù)getenv簡(jiǎn)介和使用實(shí)例
這篇文章主要介紹了PHP函數(shù)getenv簡(jiǎn)介和使用實(shí)例,getenv函數(shù)主要用來(lái)獲取一個(gè)環(huán)境變量的值,常見(jiàn)的PHP探針程序都是使用的getenv函數(shù),需要的朋友可以參考下2014-05-05