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)于后置中間件。
到此這篇關(guān)于Yii中特殊行為ActionFilter使用的文章就介紹到這了,更多相關(guān)Yii特殊行為ActionFilter使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
PHP封裝分頁函數(shù)實現(xiàn)文本分頁和數(shù)字分頁
本文主要是給大家分享了一段PHP的封裝好的分頁函數(shù),可以實現(xiàn)文本分頁和數(shù)字分頁兩種形式,非常的實用,有需要的朋友可以參考下2014-10-10
用HTML/JS/PHP方式實現(xiàn)頁面延時跳轉(zhuǎn)的簡單實例
下面小編就為大家?guī)硪黄肏TML/JS/PHP方式實現(xiàn)頁面延時跳轉(zhuǎn)的簡單實例。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-07-07
thinkPHP5框架實現(xiàn)分頁查詢功能的方法示例
這篇文章主要介紹了thinkPHP5框架實現(xiàn)分頁查詢功能的方法,結(jié)合實例形式分析了thinkPHP5實現(xiàn)分頁查詢功能的相關(guān)控制器、模板等操作技巧,需要的朋友可以參考下2018-03-03
Laravel實現(xiàn)數(shù)據(jù)庫遷移與支持中文的填充
最近在學(xué)習(xí)Laravel數(shù)據(jù)庫方面的內(nèi)容,發(fā)現(xiàn)了一些資料不錯整理出來分享給大家,下面這篇文章主要給大家介紹了關(guān)于Laravel實現(xiàn)數(shù)據(jù)庫遷移與支持中文填充的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下。2017-11-11
PHP json_encode() 函數(shù)詳解及中文亂碼問題
這篇文章主要介紹了PHP json_encode() 函數(shù)詳解及中文亂碼問題的相關(guān)資料,需要的朋友可以參考下2015-11-11
php curl獲取到j(luò)son對象并轉(zhuǎn)成數(shù)組array的方法
今天小編就為大家分享一篇php curl獲取到j(luò)son對象并轉(zhuǎn)成數(shù)組array的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-05-05

