Yii筆記之filter用法


Filter 是一個代碼片段,被配置用來在一個控制器的動作執行之前/后執行. 例如, an access control filter 可被執行以確保在執行請求的 action 之前已經過驗證; 一個 performance filter 可被用來衡量此 action 執行花費的時間.

一個 action 可有多個 filter. filter 以出現在 filter 列表中的順序來執行.一個 filter 可以阻止當前 action 及剩余未執行的 filter 的執行.

一個 filter 可被定義為一個 controller 類的方法. 此方法的名字必須以 filter 開始. 例如,方法 filterAccessControl 的存在定義了一個名為 accessControl 的 filter. 此filter 方法必須如下:public function filterAccessControl($filterChain)
{
    // call $filterChain->run() to continue filtering and action execution
}復制代碼$filterChain 是 CFilterChain 的一個實例, CFilterChain 代表了與被請求的 action 相關的 filter 列表. 在此 filter 方法內部, 我們可以調用 $filterChain->run() 以繼續 執行其他過濾器以及 action 的執行.

一個 filter 也可以是 CFilter 或其子類的一個實例. 下面的代碼定義了一個新的 filter 類:class PerformanceFilter extends CFilter
{
    protected function preFilter($filterChain)
    {
        // logic being applied before the action is executed
        return true; // false if the action should not be executed
    }
    protected function postFilter($filterChain)
    {
        // logic being applied after the action is executed
    }
}復制代碼要應用 filter 到 action, 我們需要重寫CController::filters() 方法. 此方法應當返回一個 filter 配置數組. 例如,class PostController extends CController
{
    ......
    public function filters()
    {
        return array(
            'postOnly + edit, create',
            array(
                'application.filters.PerformanceFilter - edit, create',
                'unit'=>'second',
            ),
        );
    }
}復制代碼上面的代碼指定了兩個 filter: postOnly 和 PerformanceFilter. postOnly filter 是基於方法的 (對應的 filter 方法已被定義在 CController 中); 而 PerformanceFilter filter 是基於對象的(object-based). 路徑別名 application.filters.PerformanceFilter 指定 filter 類文件是protected/filters/PerformanceFilter. 我們使用一個數組來配置PerformanceFilter 以便它可被用來初始化此 filter 對象的屬性值. 在這里 PerformanceFilter 的 unit 屬性被將初始化為 'second'.

使用+和-操作符, 我么可以指定哪個 action 此 filter 應當和不應當被應用. 在上面的例子中, postOnly 被應用到 edit 和 create action, 而 PerformanceFilter 被應用到所有的 actions 除了 edit和 create. 若+或-均未出現在 filter 配置中, 此 filter 將被用到所有 action .


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM