PHP's Yii framework filter related usage Summary, yii filter _php Tutorial

Source: Internet
Author: User

PHP's Yii framework filter related usage summary, Yii filter


About Yii Filter

A filter is a piece of code that can be configured to execute before or after the controller action executes. For example, the access control filter will be executed to ensure that the user has been authenticated before the requested action is performed, and the performance filter can be used to measure the time taken by the controller to execute.

An action can have multiple filters. The filter execution order is the order in which they appear in the filter list. Filters can block actions and other filters that follow.

Filters are written in two ways:

    • Method-based filters
    • Filters based on custom filter classes

Regardless of the filter, you must override the controller's public Function filters () method in the controller to set which filter will work for which action.

Method-based filters

To write a method-based filter, go through three steps:

Write the Action (action) in the controller;
To write the filter function in the controller, the function name must be prefixed with filter, for example: function Filteraccesscontrol ();
Overrides the Filters () method of the parent class Ccontroller, which defines the relationship between the filter and the action;
Instance:

<?php      class Usercontroller extends ccontroller{     * *      * First step: Create action *       /function Actionadd () {          echo "Actionadd";       }       /**       * Step Two: Create a method-based filter        *       /Public Function Filteraddfilter ($filterChain) {         echo " Method-based filter Usercontroller.filteradd
"; $filterChain->run (); } /** * Step three: Override the Filters () method of the parent class Ccontroller to define the relationship between the filter and the action * @see ccontroller::filters () */public function Filters () { return Array ( //define the relationship between the filter and the action ' addfilter + add ',// Array (// ' Application.filters.TestFilter ', // ), ); }

Custom Filter Classes

To customize the filter class, you need to write a filter class separately and inherit the Cfilter class, overriding some of the methods under the Cfilter class. You can look at the code of the Cfilter class, this kind of code is not much, or it is easy to read.

Custom Filter Instances:

<?php class Testfilter extends cfilter{   /**    * Performs the pre-action filtering.    * @param Cfilterchain $filterChain the filter chain.    * @return Boolean whether the filtering process should continue and the action    * should be executed.    *   /protected function Prefilter ($filterChain)   {     echo '--->testfilter.prefilter.
"; return true; } /** * Performs the post-action filtering. * @param Cfilterchain $filterChain the filter chain. * /protected function Postfilter ($filterChain) { echo '--->testfilter.postfilter.
";


Register the custom filter binding relationship with the action in the controller:

/*** Step three: Rewrite the filters () method of the parent class Ccontroller to define the relationship between the filter and the action * @see ccontroller::filters () */ublic function filters () {return array (   //define the correlation between filters and actions     ' addfilter + add ',       array (           ' Application.filters.TestFilter ',                 ),      


I have customized a filter: Testfilter, inherits the Cfilter class, overrides the two main methods of the Cfilter class: Prefilter (Front controller, run before action execution) and Postfilter (rear controller, run after action execution).

Order of execution of the two controllers

Assuming that I bind the custom filter class written above to the action Actionadd, the custom filter inherits from the parent class Cfilter two methods: Prefilter and Postfilter, and what is the order of execution between the actionadd of the binding?

After trial, the order of execution is: cfilter::p refilter--------->usercontroller::actionadd--------->cfilter::p ostfilter.

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

So the beginning of the article says, "Filters can stop the action and the execution of other filters in the back."

Read the Cfilter: The official notes of the:p Refilter know:

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

Cfilter::p refilter function default return
True; that is, the following actions and post filters are executed by default. If in the custom filter class, override Cfilter::p the Refilter method, and return
False to prevent subsequent actions and filters from executing!


Using filters

Filters are essentially a special kind of behavior, so using filters is the same as using behavior. You can override its Yii\base\controller::behaviors () method in the Controller class to declare the filter 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 for the controller class is applied by default to all actions of that class, and you can configure the Yii\base\actionfilter::only property to explicitly specify which actions the controller applies to. In the above example, the HttpCache filter applies only to index and view actions. You can also configure the Yii\base\actionfilter::except property so that some actions do not execute the filter.

In addition to the controller, the filter can be declared in the module or in the application body. Once declared, the filter is applied to all controller actions that belong to the module or application body, unless the yii\base\actionfilter::only and Yii\base\actionfilter::except properties of the filter are configured as described above.

Add: Declare filters in the module or application body, use routes instead of action IDs in the Yii\base\actionfilter::only and Yii\base\actionfilter::except properties, Because only the action ID is used in the module or in the application body, it cannot be uniquely assigned to a specific action.
When an action has multiple filters, it is executed according to the following rules:

Pre-filtration

    • Executes the filters listed in behaviors () in the application body sequentially.
    • Sequentially executes the filters listed in behaviors () in the module.
    • Sequentially executes the filters listed in behaviors () in the controller.
    • If any filter terminates the action execution, subsequent filters (including pre-and post-filtering) are no longer executed.
    • The action is performed successfully by pre-filtering.

Post-Filtration

    • Reverse executes the filter listed in behaviors () in the controller.
    • The filters listed in behaviors () in the reverse execution module.
    • Reverse executes the filter listed in behaviors () in the application body.

Creating filters

Inherit the Yii\base\actionfilter class and overwrite yii\base\actionfilter::beforeaction () and/or yii\base\actionfilter::afteraction () method to create a filter for an action that executes before the action executes, which executes after the action executes. The Yii\base\actionfilter::beforeaction () return value determines whether the action should be executed, and if False, subsequent filters and actions do not continue.

The following example declares a filter that records the execution time log of an action.

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);}  }


Core Filter

Yii provides a set of commonly used filters, under the Yii\filters namespace, and we'll briefly introduce these filters.

1.yii\filters\accesscontrol

AccessControl provides access control based on yii\filters\accesscontrol::rules rules. In particular, the access control detects all rules and finds the rules for the first context-sensitive variable (such as the user's IP address, login status, and so on) before the action is executed to determine whether the execution of the request action is allowed or denied, and if no rules are met, access is denied.

The following example indicates that an authenticated user is allowed to access the Create and update actions, denying other users access to the two actions.

Use Yii\filters\accesscontrol;public function Behaviors () {  return [    ' access ' + = '      class ' = = Accesscontrol::classname (),      ' only ' = = [' Create ', ' Update '],      ' rules ' = [        //Allow authenticated Users        [          ' Allow ' = ' = True,          ' roles ' = [' @ '],        ],        //default to other users      ],]    ,  ];}


2. Authentication Method Filter

Authentication method Filters authenticate a user through HTTP Basic auth or OAuth, and the authentication method filter class is under the Yii\filters\auth namespace.

The following example indicates that a user can be authenticated using Yii\filters\auth\httpbasicauth, which uses a token based on the HTTP Basic authentication method. Note In order to be operational, the Yii\web\user::identityclass class must implement the Yii\web\identityinterface::findidentitybyaccesstoken () method.

Use Yii\filters\auth\httpbasicauth;public function Behaviors () {  return [    ' BasicAuth ' +      = [' class ' = > Httpbasicauth::classname (),    ],  ];}

Authentication method Filters are typically used in implementing restful APIs.

3.yii\filters\contentnegotiator

Contentnegotiator supports response content format processing and language processing. The response content format and language are determined by examining the GET parameters and the Accept HTTP header.

The following example configures Contentnegotiator to support JSON and XML response formats and English (United States) and German.

Use Yii\filters\contentnegotiator;use yii\web\response;public function behaviors () {  return [    [      ' class ' = > Contentnegotiator::classname (),      ' formats ' = [        ' Application/json ' and ' = Response::format_json,        ' Application/xml ' + response::format_xml,      ],      ' languages ' = [        ' en-us ',        ' de ',      ],    ],  ];}


The detection of response formats and languages is much simpler during the application of the principal life cycle, so the contentnegotiator design can be used to boot the filter that the component invokes. It can be configured in the application principal configuration as shown in the following example.

Use Yii\filters\contentnegotiator;use yii\web\response; ['  bootstrap ' = = ['    class ' and ' = '      contentnegotiator::classname (),      ' formats ' = [        ' Application/json ' + Response::format_json,        ' application/xml ' = Response::format_xml,      ],      ' Languages ' = = [        ' en-us ',        ' de ',      ],    ],  ],];


Supplement: If the content format and language are not detected in the request, use the formats and languages first configuration items.
4.yii\filters\httpcache

HttpCache uses the last-modified and Etag HTTP headers to implement client-side caching. For example:

Use Yii\filters\httpcache;public function Behaviors () {  return [    [      ' class '] = Httpcache::classname ( ),      ' only ' = = [' index '],      ' lastmodified ' = function ($action, $params) {        $q = new \yii\db\query (); C20/>return $q->from (' user ')->max (' Updated_at ');      },    ],  ];}


5.yii\filters\pagecache

The Pagecache implements caching of the entire page on the server side. As shown in the following example, Pagecache applies the index action, which caches the entire page 60 seconds or the number of records in the post table changes. It also saves different page versions depending on the language of the application.

Use Yii\filters\pagecache;use yii\caching\dbdependency;public function behaviors () {  return [    ' pagecache ' = > [      ' class ' = Pagecache::classname (),      ' only ' and ' = ' [' Index '],      ' duration '      Dependency ' = = [        ' class ' = + Dbdependency::classname (),        ' sql ' = ' SELECT COUNT (*) from post ',      ],      ' variations ' = [        \yii:: $app->language,      ]]    ,  ];}


6.yii\filters\ratelimiter

The Ratelimiter implements rate limiting based on the leaky bucket algorithm.

7.yii\filters\verbfilter

Verbfilter checks whether the HTTP request behavior of the request action allows execution and throws an HTTP 405 exception if not allowed. In the following example, Verbfilter specifies how the CRUD action allows the request.

Use Yii\filters\verbfilter;public function Behaviors () {  return [    ' verbs ' = + [      ' class ' = ' = ' Verbfilter: : ClassName (),      ' actions ' = = [        ' index ' = = [' Get '],        ' view ' and '  [' get '],        ' create ' = [' Get ', ' post '],        ' update ' = = [' Get ', ' put ', ' post '],        ' delete ' = [' post ', ' delete '],      ]  , ];}


8.yii\filters\cors

The cross-domain resource sharing CORS mechanism allows many resources of a Web page (such as fonts, JavaScript, and so on) to be accessed through other domain names. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism, which is forbidden by the Web browser because of the same-origin security policy for cross-domain requests. Cors defines which cross-domain requests are allowed and disallowed when the browser and server interact.

Yii\filters\cors should be defined before the authorization/authentication filter to ensure that the Cors header is sent.

Use Yii\filters\cors;use yii\helpers\arrayhelper;public function behaviors () {  return arrayhelper::merge ([    [      ' class ' = Cors::classname (),    ],  ], parent::behaviors ());


Cors can be converted to use the Cors attribute.

    • Cors[' origin ': Defines an array of allowed sources, either for [' * '] (any user) or [' http://www.myserver.net ', ' http://www.myotherserver.com ']. The default is [' * '].
    • cors[' Access-control-request-method ': Allows an array of actions such as [' GET ', ' OPTIONS ', ' HEAD ']. The default is [' GET ', ' POST ', ' PUT ', ' PATCH ', ' DELETE ', ' HEAD ', ' OPTIONS '].
    • cors[' access-control-request-headers ': Allows the header array to be requested, specifying the type header for [' * '] all type headers or [' X-request-with ']. The default is [' * '].
    • cors[' Access-control-allow-credentials ': Defines whether the current request uses a certificate, which can be true, false, or null (not set). The default is null.
    • cors[' Access-control-max-age ': Defines the valid time for the request, which defaults to 86400.

For example, the cors of the Allow source for http://www.myserver.net and way for GET, HEAD and OPTIONS are as follows:

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 ());}


You can override the default parameters to adjust the Cors header for each action. For example, adding the Access-control-allow-credentials parameter to the login action is as follows:

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 ' and ' [        ' login ' = ' = ' c18/> ' access-control-allow-credentials ' = True,        ]]]    ,  ], parent::behaviors ());}

Articles you may be interested in:

    • Introduction to some advanced usage of caching in the YII framework of PHP
    • In-depth parsing of PHP's caching capabilities in the YII framework
    • The use of view view in the Yii framework of PHP is advanced
    • A detailed approach to creating views and rendering views in the PHP yii framework
    • A tutorial on model models in the YII framework of PHP
    • Controller controllers in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework
    • The definition and binding methods of behavior in the YII framework of PHP
    • In-depth explanation of properties in the Yii framework of PHP
    • A detailed description of the use of the front-end resource bundle in PHP's YII framework

http://www.bkjia.com/PHPjc/1117067.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117067.html techarticle PHP's Yii framework filter related usage Summary, Yii filter Yii Filter Introduction filter is a piece of code, can be configured before or after the controller action execution. For example, visit ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.