YIIFramework filter usage analysis

Source: Internet
Author: User
This article mainly introduces the usage of the YIIFramework filter, and analyzes the filter function, usage skills, and related precautions in the form of examples, for more information about YII Framework filter usage, see the following example. We will share this with you for your reference. The details are as follows:

First, let's take a look at the official documentation, what is a filter, the role of a filter, filter rules, and filter definition methods.

Then, make a summary of the filter.

Http://www.yiiframework.com/doc/guide/1.1/zh_cn/basics.controller

A filter is a piece of code that can be configured to be executed before or after the controller action is executed. For example, the access control filter will be executed to ensure that the user has passed authentication before the action of the request is executed; the performance filter can be used to measure the time taken by the controller for execution.

An action can have multiple filters. The filter execution sequence is the order in which they appear in the filter list. Filters can prevent the action and other filters from being executed.

A filter can be defined as a controller class method. The method name must start with "filter. For example, the existing filterAccessControl method defines a filter named accessControl. The filter method must have the following structure:

Public function filterAccessControl ($ filterChain) {// call $ filterChain-> run () to continue the subsequent filter and action execution .}

$ FilterChain is an instance of CFilterChain, representing the list of filters related to the requested action. In the filter method, we can call $ filterChain-> run () to continue to execute subsequent filters and actions.

A filter can also be a CFilter or its subclass instance. The following code defines a new filter class:

Class PerformanceFilter extends CFilter {protected function preFilter ($ filterChain) {// The Logical return true applied before the action is executed; // if the action should not be executed, returns false} protected function postFilter ($ filterChain) {// The logic of the application after the action is executed }}

To apply a filter to an action, we need to overwrite the CController: filters () method. This method should return an array of filter configurations. For example:

class PostController extends CController{  ......  public function filters()  {    return array(      'postOnly + edit, create',      array(        'application.filters.PerformanceFilter - edit, create',        'unit'=>'second',      ),    );  }}

The above code specifies two filters: postOnly and PerformanceFilter. PostOnly filters are method-based (the corresponding filter methods have been defined in CController), while performanceFilter filters are object-based. Path alias application. filters. cecefilter specifies that the filter class file is protected/filters/cecefilter. We use an array to configure PerformanceFilter so that it can be used to initialize the attribute value of the filter object. The unit attribute value of PerformanceFilter is initially set to second.

With the addition and subtraction signs, we can specify which actions should or should not apply the filter. In the above code, postOnly should be applied only to edit and create actions, while PerformanceFilter should be applied to actions other than edit and create. If the addition and subtraction signs are not used in the filter configuration, the filter is applied to all actions.

Filter function:

Used to filter visitors and data and to record access operations

Usage:

1. as a controller method. The method name starts with "filter.

public function filterAccessControl($filterChain){ echo "--->filterAccessControl";  $filterChain->run();}

2. define the opposite filter class, requiring extends CFilter.

CFilter

<?php /**  * CFilter is the base class for all filters.  *  * A filter can be applied before and after an action is executed.  * It can modify the context that the action is to run or decorate the result that the  * action generates.  *  * Override {@link preFilter()} to specify the filtering logic that should be applied  * before the action, and {@link postFilter()} for filtering logic after the action.  *  * @author Qiang Xue 
 
    * @version $Id: CFilter.php 2799 2011-01-01 19:31:13Z qiang.xue $  * @package system.web.filters  * @since 1.0  */ class CFilter extends CComponent implements IFilter {   /**    * Performs the filtering.    * The default implementation is to invoke {@link preFilter}    * and {@link postFilter} which are meant to be overridden    * child classes. If a child class needs to override this method,    * make sure it calls 
  $filterChain->run()    * if the action should be executed.    * @param CFilterChain $filterChain the filter chain that the filter is on.    */   public function filter($filterChain)   {     if($this->preFilter($filterChain))     {       $filterChain->run();       $this->postFilter($filterChain);     }   }   /**    * Initializes the filter.    * This method is invoked after the filter properties are initialized    * and before {@link preFilter} is called.    * You may override this method to include some initialization logic.    * @since 1.1.4    */   public function init()   {   }   /**    * 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)   {     return true;   }   /**    * Performs the post-action filtering.    * @param CFilterChain $filterChain the filter chain that the filter is on.    */   protected function postFilter($filterChain)   {   } }
 

The following is an example of the use of the two filter rules:

SiteController. php

<?php class SiteController extends Controller {   public function init()   {     //$this->layout='mylayout';   }   public function filters()     {       return array(         'AccessControl - create',         array(           'application.filters.MyFilter + create',         ),       );   }   public function filterAccessControl($filterChain)   {           echo "--->filterAccessControl";       $filterChain->run();   }   public function actionCreate() {     echo "--->create action";   }   public function actionPrint() {     echo "--->print action";   } 

/Www/yii_dev/testwebap/protected # tree
.
── Commands
│ ── Shell
│ ── TestCommand. php
│ ── TestCommand. php ~
── Components
│ ── Controller. php
│ ── UserIdentity. php
── Config
│ ── Console. php
│ ── Main. php
│ └ ── Test. php
├ ── Controllers
│ ── Post
│ ── UpdateAction. php
│ ── SiteController. php
│ ── TestTestController. php
│ ── UserController. php
── Filters
│ ── MyFilter. php
MyFilter. php

<?php class MyFilter extends CFilter {   protected function preFilter ($filterChain)   {     // logic being applied before the action is executed         echo "-->MyFilter-->pre";     return true; // false if the action should not be executed   }   protected function postFilter ($filterChain)   {     echo "-->MyFilter-->post";   } } 

Http://www.localyii.com/testwebap/index.php? R = site/print

---> FilterAccessControl ---> print action

Http://www.localyii.com/testwebap/index.php? R = site/create

--> MyFilter --> pre ---> create action --> MyFilter --> post

public function filters(){  return array(    'AccessControl - create',    array(      'application.filters.MyFilter + create,print',    ),  );}

Http://www.localyii.com/testwebap/index.php? R = site/print
---> FilterAccessControl --> MyFilter --> pre ---> print action --> MyFilter --> post

You can see the specific execution process of the filter.

In filters, there are-, +
The specific function is
+ Indicates that only these actions are valid.
-List of the names of the following actions. Exclusive.
If no-or + exists, all actions will be applied.

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.