Filter-related Usage summary _php tips in the Yii framework of PHP

Source: Internet
Author: User
Tags auth yii

Introduction to Yii Filter

A filter is a piece of code that can be configured to execute before or after the controller action is executed. For example, an access control filter is executed to ensure that the user is authenticated before the requested action is performed, and the performance filter can be used to measure the time spent by the controller's execution.

An action can have more than one filter. 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:

    • A method based filter
    • Filters based on custom filter classes

Whichever filter you have, you must override the controller's public Function filters () method in the controller to set which filter works for which action.

A method based filter

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

Write the Action (action) in the controller;
To write a 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 the filter and the action;
Instance:

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

Custom Filter Class

Custom filter class, you need to write a separate filter class, and inherit the Cfilter class, overriding some of the methods under the Cfilter class. You can look at the code of the Cfilter class, the code is not much, it is easy to read.

Custom Filter Instance:

<?php 
class Testfilter extends cfilter{ 
  /** performs 
   * pre-action. 
   * @param Cfilterchain $filterChain The filter chain that's 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's on. 
   * 
  /protected function Postfilter ($filterChain) 
  { 
    echo "--->TestFilter.postFilter.<br>"; 
  } 
} 


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

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


I've customized a filter: Testfilter, which inherits the Cfilter class, overrides the two main methods of the Cfilter class: Prefilter (the former controller, run before the action), and Postfilter (the rear controller, which runs after the action is executed).

Order of execution of the two kinds of controllers

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

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 performed.

So how did the article begin by saying, "The filter can stop the action and the rest of the filter's execution"?

Read the Cfilter::p Refilter's official note to know:

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

Cfilter::p refilter function default return
true; The following action and the back filter are performed by default. If you override Cfilter in a custom filter class::p Refilter method, and return
false; You can 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 to all actions of the class by default, 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 the index and view actions. You can also configure the Yii\base\actionfilter::except property so that some actions do not perform a filter.

In addition to the controller, you can declare the filter in the module or application body. Once declared, the filter is applied to all controller actions that belong to the module or to the 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 routing in Yii\base\actionfilter::only and Yii\base\actionfilter::except properties to replace action IDs, Because only the action ID is used in a module or application body, you cannot specify a specific action.
When an action has more than one filter, it is executed according to the following rules:

Pre-filtration

    • Executes the filters listed in the behaviors () in the application body sequentially.
    • Executes the filters listed in behaviors () in the module sequentially.
    • The filters listed in behaviors () in the controller are executed sequentially.
    • If any filter terminates the execution of the action, subsequent filters (including pre filtering and filtering) are no longer executed.
    • Performs the action after the filter has been successfully passed.

Filter After

    • In reverse execution, the filter listed in behaviors () in the controller.
    • The filter listed in the Behaviors () in the reverse execution module.
    • Reverse executes the filters listed in the 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 the action, which executes before the action executes, and the latter executes after the action is executed. The Yii\base\actionfilter::beforeaction () return value determines whether the action should be performed 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 Filters

Yii provides a common set of filters, under the Yii\filters namespace, and then we briefly introduce these filters.

1.yii\filters\accesscontrol

AccessControl provides access control based on yii\filters\accesscontrol::rules rules. In particular, before the action is executed, access control detects all the rules and finds the rules for the first context-compliant variable (such as User IP address, login status, and so on) to decide whether to allow or reject the execution of the requested action, 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 and deny 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 user
        [
          ' Allow ' => true,
          ' roles ' => [' @ '],
        ],
        ///By default prohibit other users
      ],],]
  ;
}


2. Authentication Method Filter

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

The following example indicates that you can use Yii\filters\auth\httpbasicauth to authenticate a user using a token based on the HTTP base 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 usually used in implementing the RESTful API.

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 Accept HTTP headers.

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 ' => response::format_json,
        ' application/xml ' => response::format_ XML,
      ],
      ' languages ' => [
        ' en-us ',
        ' de ',],],]
  ;
}


The response format and language are much simpler to detect in the application principal lifecycle process, so contentnegotiator designs filters that can be invoked by the boot component. 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 ' => contentnegotiator::classname (),
      ' formats ' =>
        ' Application/json ' => Response::format_json,
        ' application/xml ' => response::format_xml,
      ],
      ' Languages ' => [
        ' en-us ',
        ' de ',],],],]
;


Add: If the content format and language are not detected in the request, the first configuration item is used formats and languages.
4.yii\filters\httpcache

HttpCache uses 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 ();
        return $q->from (' user ')->max (' Updated_at ');
      },
    ]
  ;



5.yii\filters\pagecache

Pagecache implements caching of entire pages on the server side. As shown in the following example, Pagecache is applied to the index action, caching the entire page for 60 seconds or the number of records in the post table has changed. It also saves different page versions according to the different application languages.

Use Yii\filters\pagecache;
Use yii\caching\dbdependency;

Public function behaviors ()
{return
  [
    ' Pagecache ' => ['
      class ' => pagecache::classname (),
      ' Only ' => [' index '],
      ' duration ' =>,
      ' dependency ' => [
        ' class ' => dbdependency::classname () ,
        ' sql ' => ' SELECT COUNT (*) from post ',
      ],
      ' variations ' => [
        \yii:: $app->language,
      ]
    ],
  ];
}


6.yii\filters\ratelimiter

Ratelimiter based on the leaky bucket algorithm to achieve rate limits.

7.yii\filters\verbfilter

Verbfilter checks whether the HTTP request for the requested action is allowed to execute and throws an HTTP 405 exception if not allowed. The following example verbfilter specifies the type of request allowed by the CRUD action.

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

Cross-domain resource sharing CORS mechanism allows many resources (such as fonts, JavaScript, etc.) of a Web page to be accessed through other domain names. In particular JavaScript ' s AJAX calls can use the XMLHttpRequest mechanism, because the Cross-domain request is banned by the Web browser because of the homology security policy. Cors defines which cross-domain requests are allowed and prohibited when the browser interacts with the server.

Yii\filters\cors should be defined prior to the authorization/authentication filter to ensure that Cors headers are sent.

Use yii\filters\cors;
Use Yii\helpers\arrayhelper;

The Public Function behaviors ()
{return
  arrayhelper::merge ([
    [
      ' class ' => cors::classname (),
    ],
  ], parent::behaviors ());



Cors can be converted to use the Cors property.

    • cors[' Origin ': Defines an array of allowed sources, either [' * '] (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 an array of headers to be requested, which can be specified for all type headers of [' * '] or [' X-request-with ']. The default is [' * '].
    • cors[' Access-control-allow-credentials ': Defines whether the current request uses a certificate, can be true, false, or null (not set). The default is null.
    • cors[' Access-control-max-age ': Defines a valid time for the request, which defaults to 86400.

For example, allow the source to be http://www.myserver.net and the way to get the head and OPTIONS cors 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 parameter to adjust the Cors head for each action. For example, adding the Access-control-allow-credentials parameter to the login action looks like this:

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


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.