国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
A summary of the use of filters in PHP's Yii framework, yii filters
Articles you may be interested in:
Home Backend Development PHP Tutorial Summary of the use of filters in PHP's Yii framework, yii filter_PHP tutorial

Summary of the use of filters in PHP's Yii framework, yii filter_PHP tutorial

Jul 12, 2016 am 08:55 AM
php phpexcel yii

A summary of the use of filters in PHP's Yii framework, yii filters

Introduction to Yii filters

A filter is a piece of code that can be configured to execute before or after a controller action. For example, access control filters will be executed to ensure that the user is authenticated before performing the requested action; performance filters can be used to measure the time it takes for the controller to execute.

An action can have multiple filters. Filters are executed in the order they appear in the filter list. Filters can prevent actions and other subsequent filters from executing.

There are two ways to write filters:

  • Method-based filters
  • Filter based on custom filter class

No matter what kind of filter you use, you must override the controller's public function filters() method in the controller to set which filter will act on which action.

Method-based filters

Writing a method-based filter requires three steps:

Write actions in the controller;
Write the filter function in the controller. The function name must be prefixed with filter, such as: function filterAccessControl();
Rewrite the filters() method of the parent class CController to define the relationship between filters and actions;
Example:

<&#63;php 
   
  class UserController extends CController{ 
    ** 
     * 第一步:創(chuàng)建動作 
     */ 
      function actionAdd(){  
        echo "actionAdd"; 
      } 
      /** 
      * 第二步:創(chuàng)建基于方法的過濾器 
       */ 
      public function filterAddFilter($filterChain) { 
        echo "基于方法的過濾器UserController.filterAdd<br>"; 
        $filterChain->run(); 
      } 
      /** 
      * 第三步:重寫父類CController的filters()方法,定義過濾器與動作的關(guān)系 
      * @see CController::filters() 
      */ 
      public function filters(){ 
        return array( 
      //定義過濾器與動作的關(guān)聯(lián)關(guān)系 
          'addFilter + add', 
//         array( 
//             'application.filters.TestFilter',           
//         ), 
           
      ); 
    } 
  } 

Custom filter class

To customize the filter class, you need to write a separate filter class, inherit the CFilter class, and override some methods under the CFilter class. You can take a look at the code of the CFilter class. There is not much code in this class and it is still easy to understand.

Custom filter example:

<&#63;php 
class TestFilter extends CFilter{ 
  /** 
   * Performs the pre-action filtering. 
   * @param CFilterChain $filterChain the filter chain that the filter is on. 
   * @return boolean whether the filtering process should continue and the action 
   * should be executed. 
   */ 
  protected function preFilter($filterChain) 
  { 
    echo "--->TestFilter.preFilter.<br>"; 
    return true; 
  } 
   
  /** 
   * Performs the post-action filtering. 
   * @param CFilterChain $filterChain the filter chain that the filter is on. 
   */ 
  protected function postFilter($filterChain) 
  { 
    echo "--->TestFilter.postFilter.<br>"; 
  } 
} 


Register the binding relationship between the custom filter and the action in the controller:

/**
* 第三步:重寫父類CController的filters()方法,定義過濾器與動作的關(guān)系 
* @see CController::filters() 
*/ 
ublic function filters(){ 
return array( 
  //定義過濾器與動作的關(guān)聯(lián)關(guān)系 
    'addFilter + add', 
      array( 
          'application.filters.TestFilter',           
      ), 
     
); 


I customized a filter: TestFilter, which inherits the CFilter class and overrides the two main methods of the CFilter class: preFilter (pre-controller, runs before the action is executed) and postFilter (post-controller, runs after the action is executed) ).

Execution sequence of the two controllers

Suppose I bind the custom filter class written above to the actionAdd. Then, the custom filter inherits two methods from the parent class CFilter: preFilter and postFilter, and the execution order with the bound actionAdd is What kind of thing?

After testing, the execution order is: CFilter::preFilter--------->UserController::actionAdd--------->CFilter::postFilter.

In other words, filtering operations can be performed before and after the action is executed.

So how does it say at the beginning of the article that "Filters can prevent the execution of actions and other subsequent filters"?

You will know after reading the official comments of CFilter::preFilter:

@return boolean whether the filtering process should continue and the action should be executed.

CFilter::preFilter function returns by default
true; that is, subsequent actions and post-filters are executed by default. If in a custom filter class, override the CFilter::preFilter method and return
False; you can prevent subsequent actions and filters from executing!


Use filters

A filter is essentially a special type of behavior, so using a filter is the same as using a behavior. Filters can be declared in the controller class by overriding its yiibaseController::behaviors() method as follows:

public function behaviors()
{
  return [
    [
      'class' => 'yii\filters\HttpCache',
      'only' => ['index', 'view'],
      'lastModified' => function ($action, $params) {
        $q = new \yii\db\Query();
        return $q->from('user')->max('updated_at');
      },
    ],
  ];
}

The filter of a controller class is applied to all actions of the class by default. You can configure the yiibaseActionFilter::only attribute to explicitly specify which actions the controller applies to. In the above example, the HttpCache filter only applies to index and view actions. You can also configure the yiibaseActionFilter::except attribute to prevent some actions from executing filters.

In addition to controllers, filters can be declared in modules or application bodies. After declaration, the filter will be applied to all controller actions belonging to the module or application body, unless the filter's yiibaseActionFilter::only and yiibaseActionFilter::except attributes are configured as above.

Supplement: When declaring filters in the module or application body, use routes instead of action IDs in the yiibaseActionFilter::only and yiibaseActionFilter::except attributes, because only using the action ID in the module or application body cannot uniquely specify the specific action. .
When an action has multiple filters, they are executed sequentially according to the following rules:

Pre-filter

  • Execute the filters listed in behaviors() in the application body in order.
  • Execute the filters listed in behaviors() in the module in order.
  • Execute the filters listed in behaviors() in the controller in order.
  • If any filter terminates action execution, subsequent filters (including pre-filtering and post-filtering) will no longer be executed.
  • Execute the action after successfully passing pre-filtering.

Post filter

  • Execute the filters listed in behaviors() in the controller in reverse order.
  • Execute the filters listed in behaviors() in the module in reverse order.
  • Execute the filters listed in behaviors() in the application body in reverse order.

Create filter

繼承 yii\base\ActionFilter 類并覆蓋 yii\base\ActionFilter::beforeAction() 和/或 yii\base\ActionFilter::afterAction() 方法來創(chuàng)建動作的過濾器,前者在動作執(zhí)行之前執(zhí)行,后者在動作執(zhí)行之后執(zhí)行。 yii\base\ActionFilter::beforeAction() 返回值決定動作是否應(yīng)該執(zhí)行, 如果為false,之后的過濾器和動作不會繼續(xù)執(zhí)行。

下面的例子申明一個記錄動作執(zhí)行時間日志的過濾器。

namespace app\components;

use Yii;
use yii\base\ActionFilter;

class ActionTimeFilter extends ActionFilter
{
  private $_startTime;

  public function beforeAction($action)
  {
    $this->_startTime = microtime(true);
    return parent::beforeAction($action);
  }

  public function afterAction($action, $result)
  {
    $time = microtime(true) - $this->_startTime;
    Yii::trace("Action '{$action->uniqueId}' spent $time second.");
    return parent::afterAction($action, $result);
  }
}


核心過濾器

Yii提供了一組常用過濾器,在yii\filters命名空間下,接下來我們簡要介紹這些過濾器。

1.yii\filters\AccessControl

AccessControl提供基于yii\filters\AccessControl::rules規(guī)則的訪問控制。 特別是在動作執(zhí)行之前,訪問控制會檢測所有規(guī)則并找到第一個符合上下文的變量(比如用戶IP地址、登錄狀態(tài)等等)的規(guī)則, 來決定允許還是拒絕請求動作的執(zhí)行,如果沒有規(guī)則符合,訪問就會被拒絕。

如下示例表示表示允許已認(rèn)證用戶訪問create 和 update 動作,拒絕其他用戶訪問這兩個動作。

use yii\filters\AccessControl;

public function behaviors()
{
  return [
    'access' => [
      'class' => AccessControl::className(),
      'only' => ['create', 'update'],
      'rules' => [
        // 允許認(rèn)證用戶
        [
          'allow' => true,
          'roles' => ['@'],
        ],
        // 默認(rèn)禁止其他用戶
      ],
    ],
  ];
}


2.認(rèn)證方法過濾器

認(rèn)證方法過濾器通過HTTP Basic Auth或OAuth 2 來認(rèn)證一個用戶,認(rèn)證方法過濾器類在 yii\filters\auth 命名空間下。

如下示例表示可使用yii\filters\auth\HttpBasicAuth來認(rèn)證一個用戶,它使用基于HTTP基礎(chǔ)認(rèn)證方法的令牌。 注意為了可運行,yii\web\User::identityClass 類必須 實現(xiàn) yii\web\IdentityInterface::findIdentityByAccessToken()方法。

use yii\filters\auth\HttpBasicAuth;

public function behaviors()
{
  return [
    'basicAuth' => [
      'class' => HttpBasicAuth::className(),
    ],
  ];
}

認(rèn)證方法過濾器通常在實現(xiàn)RESTful API中使用。

3.yii\filters\ContentNegotiator

ContentNegotiator支持響應(yīng)內(nèi)容格式處理和語言處理。 通過檢查 GET 參數(shù)和 Accept HTTP頭部來決定響應(yīng)內(nèi)容格式和語言。

如下示例,配置ContentNegotiator支持JSON和XML響應(yīng)格式和英語(美國)和德語。

use yii\filters\ContentNegotiator;
use yii\web\Response;

public function behaviors()
{
  return [
    [
      'class' => ContentNegotiator::className(),
      'formats' => [
        'application/json' => Response::FORMAT_JSON,
        'application/xml' => Response::FORMAT_XML,
      ],
      'languages' => [
        'en-US',
        'de',
      ],
    ],
  ];
}


在應(yīng)用主體生命周期過程中檢測響應(yīng)格式和語言簡單很多, 因此ContentNegotiator設(shè)計可被引導(dǎo)啟動組件調(diào)用的過濾器。 如下例所示可以將它配置在應(yīng)用主體配置。

use yii\filters\ContentNegotiator;
use yii\web\Response;

[
  'bootstrap' => [
    [
      'class' => ContentNegotiator::className(),
      'formats' => [
        'application/json' => Response::FORMAT_JSON,
        'application/xml' => Response::FORMAT_XML,
      ],
      'languages' => [
        'en-US',
        'de',
      ],
    ],
  ],
];


補(bǔ)充: 如果請求中沒有檢測到內(nèi)容格式和語言,使用formats和languages第一個配置項。
4.yii\filters\HttpCache

HttpCache利用Last-Modified 和 Etag HTTP頭實現(xiàn)客戶端緩存。例如:

use yii\filters\HttpCache;

public function behaviors()
{
  return [
    [
      'class' => HttpCache::className(),
      'only' => ['index'],
      'lastModified' => function ($action, $params) {
        $q = new \yii\db\Query();
        return $q->from('user')->max('updated_at');
      },
    ],
  ];
}


5.yii\filters\PageCache

PageCache實現(xiàn)服務(wù)器端整個頁面的緩存。如下示例所示,PageCache應(yīng)用在index動作, 緩存整個頁面60秒或post表的記錄數(shù)發(fā)生變化。它也會根據(jù)不同應(yīng)用語言保存不同的頁面版本。

use yii\filters\PageCache;
use yii\caching\DbDependency;

public function behaviors()
{
  return [
    'pageCache' => [
      'class' => PageCache::className(),
      'only' => ['index'],
      'duration' => 60,
      'dependency' => [
        'class' => DbDependency::className(),
        'sql' => 'SELECT COUNT(*) FROM post',
      ],
      'variations' => [
        \Yii::$app->language,
      ]
    ],
  ];
}


6.yii\filters\RateLimiter

RateLimiter 根據(jù) 漏桶算法 來實現(xiàn)速率限制。

7.yii\filters\VerbFilter

VerbFilter檢查請求動作的HTTP請求方式是否允許執(zhí)行,如果不允許,會拋出HTTP 405異常。 如下示例,VerbFilter指定CRUD動作所允許的請求方式。

use yii\filters\VerbFilter;

public function behaviors()
{
  return [
    'verbs' => [
      'class' => VerbFilter::className(),
      'actions' => [
        'index' => ['get'],
        'view'  => ['get'],
        'create' => ['get', 'post'],
        'update' => ['get', 'put', 'post'],
        'delete' => ['post', 'delete'],
      ],
    ],
  ];
}


8.yii\filters\Cors

跨域資源共享 CORS 機(jī)制允許一個網(wǎng)頁的許多資源(例如字體、JavaScript等) 這些資源可以通過其他域名訪問獲取。 特別是JavaScript's AJAX 調(diào)用可使用 XMLHttpRequest 機(jī)制,由于同源安全策略該跨域請求會被網(wǎng)頁瀏覽器禁止. CORS定義瀏覽器和服務(wù)器交互時哪些跨域請求允許和禁止。

yii\filters\Cors 應(yīng)在 授權(quán) / 認(rèn)證 過濾器之前定義,以保證CORS頭部被發(fā)送。

use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
  return ArrayHelper::merge([
    [
      'class' => Cors::className(),
    ],
  ], parent::behaviors());
}


Cors 可轉(zhuǎn)為使用 cors 屬性。

  • cors['Origin']: 定義允許來源的數(shù)組,可為['*'] (任何用戶) 或 ['http://www.myserver.net', 'http://www.myotherserver.com']. 默認(rèn)為 ['*'].
  • cors['Access-Control-Request-Method']: 允許動作數(shù)組如 ['GET', 'OPTIONS', 'HEAD']. 默認(rèn)為 ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].
  • cors['Access-Control-Request-Headers']: 允許請求頭部數(shù)組,可為 ['*'] 所有類型頭部 或 ['X-Request-With'] 指定類型頭部. 默認(rèn)為 ['*'].
  • cors['Access-Control-Allow-Credentials']: 定義當(dāng)前請求是否使用證書,可為 true, false 或 null (不設(shè)置). 默認(rèn)為null.
  • cors['Access-Control-Max-Age']: 定義請求的有效時間,默認(rèn)為 86400.

例如,允許來源為 http://www.myserver.net 和方式為 GET, HEAD 和 OPTIONS 的CORS如下:

use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
  return ArrayHelper::merge([
    [
      'class' => Cors::className(),
      'cors' => [
        'Origin' => ['http://www.myserver.net'],
        'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
      ],
    ],
  ], parent::behaviors());
}


可以覆蓋默認(rèn)參數(shù)為每個動作調(diào)整CORS 頭部。例如,為login動作增加Access-Control-Allow-Credentials參數(shù)如下所示:

use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
{
  return ArrayHelper::merge([
    [
      'class' => Cors::className(),
      'cors' => [
        'Origin' => ['http://www.myserver.net'],
        'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
      ],
      'actions' => [
        'login' => [
          'Access-Control-Allow-Credentials' => true,
        ]
      ]
    ],
  ], parent::behaviors());
}

Articles you may be interested in:

  • Introduction to some advanced usage of caching in PHP's Yii framework
  • In-depth analysis of the caching function in PHP's Yii framework
  • Advanced use of View in PHP's Yii framework
  • Detailed explanation of the methods of creating and rendering views in PHP's Yii framework
  • Study tutorial on Model model in PHP's Yii framework
  • Detailed explanation of the Controller controller in PHP's Yii framework
  • How to remove the behavior bound to a component in PHP's Yii framework
  • The definition and definition of behavior in PHP's Yii framework Explanation of binding methods
  • In-depth explanation of properties (Property) in PHP's Yii framework
  • Detailed explanation of the use of the front-end resource package that comes with PHP's Yii framework

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1117067.htmlTechArticleA summary of the use of filters in PHP's Yii framework, yii filter Yii filter introduction A filter is a piece of code , can be configured to execute before or after the controller action is executed. For example, visit...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

How do I use page caching in PHP? How do I use page caching in PHP? Jun 24, 2025 am 12:50 AM

PHP page caching improves website performance by reducing server load and speeding up page loading. 1. Basic file cache avoids repeated generation of dynamic content by generating static HTML files and providing services during the validity period; 2. Enable OPcache to compile PHP scripts into bytecode and store them in memory, improving execution efficiency; 3. For dynamic pages with parameters, they should be cached separately according to URL parameters, and avoid cached user-specific content; 4. Lightweight cache libraries such as PHPFastCache can be used to simplify development and support multiple storage drivers. Combining these methods can effectively optimize the caching strategy of PHP projects.

How to quickly test PHP code snippets? How to quickly test PHP code snippets? Jun 25, 2025 am 12:58 AM

ToquicklytestaPHPcodesnippet,useanonlinePHPsandboxlike3v4l.orgorPHPize.onlineforinstantexecutionwithoutsetup;runcodelocallywithPHPCLIbycreatinga.phpfileandexecutingitviatheterminal;optionallyusephp-rforone-liners;setupalocaldevelopmentenvironmentwith

How do I use logical operators in PHP (&&, ||, !, and, or, xor)? How do I use logical operators in PHP (&&, ||, !, and, or, xor)? Jun 23, 2025 am 12:56 AM

In PHP, logical operators are used to combine or evaluate conditions, and the main operators include &&, and, ||, or, !, and xor. 1. The difference between && and is in priority. && is higher than the assignment operator, while and is lower than the assignment operator, so the behavior is different when combining assignment; 2.|| and or also have similar priority differences, || takes precedence over assignment, while or is processed after assignment; 3.! operator is used to invert Boolean values, often used to check whether the condition is false, and it is recommended to wrap complex expressions in brackets to ensure correct application; 4.xor returns true only when exactly one of the two values ??is true, suitable for mutex condition judgment

See all articles