這篇文章主要講解了“如何使用Yii里的特別行為ActionFilter”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“如何使用Yii里的特別行為ActionFilter”吧!
新建 app\filters\LoggingFilter 繼承 yii\base\ActionFilter
LoggingFilter 的功能: 在指定請求的 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'], // 僅對 '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); } }
測試
請求 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.
請求 http://yii.test/index.php?r=system/test-one
This is a testing for system/test-one.
請求 http://yii.test/index.php?r=system/test-two
This is a testing for system/test-two.
總結(jié)
Yii 中的 ActionFilter(過濾器)相當(dāng)于 Laravel 中的 Middleware(中間件),beforeAction 相當(dāng)于前置中間件,afterAction 相當(dāng)于后置中間件。
感謝各位的閱讀,以上就是“如何使用Yii里的特別行為ActionFilter”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對如何使用Yii里的特別行為ActionFilter這一問題有了更深刻的體會,具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司,,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!
本文標(biāo)題:如何使用Yii里的特別行為ActionFilter-創(chuàng)新互聯(lián)
本文URL:http://www.rwnh.cn/article30/pjhso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務(wù)器、關(guān)鍵詞優(yōu)化、外貿(mào)網(wǎng)站建設(shè)、移動網(wǎng)站建設(shè)、網(wǎng)站營銷、定制開發(fā)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容