国产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)建動(dòng)作 
     */ 
      function actionAdd(){  
        echo "actionAdd"; 
      } 
      /** 
      * 第二步:創(chuàng)建基于方法的過(guò)濾器 
       */ 
      public function filterAddFilter($filterChain) { 
        echo "基于方法的過(guò)濾器UserController.filterAdd<br>"; 
        $filterChain->run(); 
      } 
      /** 
      * 第三步:重寫(xiě)父類(lèi)CController的filters()方法,定義過(guò)濾器與動(dòng)作的關(guān)系 
      * @see CController::filters() 
      */ 
      public function filters(){ 
        return array( 
      //定義過(guò)濾器與動(dòng)作的關(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:

/**
* 第三步:重寫(xiě)父類(lèi)CController的filters()方法,定義過(guò)濾器與動(dòng)作的關(guān)系 
* @see CController::filters() 
*/ 
ublic function filters(){ 
return array( 
  //定義過(guò)濾器與動(dòng)作的關(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 類(lèi)并覆蓋 yii\base\ActionFilter::beforeAction() 和/或 yii\base\ActionFilter::afterAction() 方法來(lái)創(chuàng)建動(dòng)作的過(guò)濾器,前者在動(dòng)作執(zhí)行之前執(zhí)行,后者在動(dòng)作執(zhí)行之后執(zhí)行。 yii\base\ActionFilter::beforeAction() 返回值決定動(dòng)作是否應(yīng)該執(zhí)行, 如果為false,之后的過(guò)濾器和動(dòng)作不會(huì)繼續(xù)執(zhí)行。

下面的例子申明一個(gè)記錄動(dòng)作執(zhí)行時(shí)間日志的過(guò)濾器。

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


核心過(guò)濾器

Yii提供了一組常用過(guò)濾器,在yii\filters命名空間下,接下來(lái)我們簡(jiǎn)要介紹這些過(guò)濾器。

1.yii\filters\AccessControl

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

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

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)證方法過(guò)濾器

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

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

use yii\filters\auth\HttpBasicAuth;

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

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

3.yii\filters\ContentNegotiator

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

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

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)用主體生命周期過(guò)程中檢測(cè)響應(yīng)格式和語(yǔ)言簡(jiǎn)單很多, 因此ContentNegotiator設(shè)計(jì)可被引導(dǎo)啟動(dòng)組件調(diào)用的過(guò)濾器。 如下例所示可以將它配置在應(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ǔ)充: 如果請(qǐng)求中沒(méi)有檢測(cè)到內(nèi)容格式和語(yǔ)言,使用formats和languages第一個(gè)配置項(xiàng)。
4.yii\filters\HttpCache

HttpCache利用Last-Modified 和 Etag HTTP頭實(shí)現(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實(shí)現(xiàn)服務(wù)器端整個(gè)頁(yè)面的緩存。如下示例所示,PageCache應(yīng)用在index動(dòng)作, 緩存整個(gè)頁(yè)面60秒或post表的記錄數(shù)發(fā)生變化。它也會(huì)根據(jù)不同應(yīng)用語(yǔ)言保存不同的頁(yè)面版本。

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ù) 漏桶算法 來(lái)實(shí)現(xiàn)速率限制。

7.yii\filters\VerbFilter

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

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ī)制允許一個(gè)網(wǎng)頁(yè)的許多資源(例如字體、JavaScript等) 這些資源可以通過(guò)其他域名訪問(wèn)獲取。 特別是JavaScript's AJAX 調(diào)用可使用 XMLHttpRequest 機(jī)制,由于同源安全策略該跨域請(qǐng)求會(huì)被網(wǎng)頁(yè)瀏覽器禁止. CORS定義瀏覽器和服務(wù)器交互時(shí)哪些跨域請(qǐng)求允許和禁止。

yii\filters\Cors 應(yīng)在 授權(quán) / 認(rèn)證 過(guò)濾器之前定義,以保證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']: 定義允許來(lái)源的數(shù)組,可為['*'] (任何用戶) 或 ['http://www.myserver.net', 'http://www.myotherserver.com']. 默認(rèn)為 ['*'].
  • cors['Access-Control-Request-Method']: 允許動(dòng)作數(shù)組如 ['GET', 'OPTIONS', 'HEAD']. 默認(rèn)為 ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].
  • cors['Access-Control-Request-Headers']: 允許請(qǐng)求頭部數(shù)組,可為 ['*'] 所有類(lèi)型頭部 或 ['X-Request-With'] 指定類(lèi)型頭部. 默認(rèn)為 ['*'].
  • cors['Access-Control-Allow-Credentials']: 定義當(dāng)前請(qǐng)求是否使用證書(shū),可為 true, false 或 null (不設(shè)置). 默認(rèn)為null.
  • cors['Access-Control-Max-Age']: 定義請(qǐng)求的有效時(shí)間,默認(rèn)為 86400.

例如,允許來(lái)源為 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ù)為每個(gè)動(dòng)作調(diào)整CORS 頭部。例如,為login動(dòng)作增加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 to use php exit function? How to use php exit function? Jul 03, 2025 am 02:15 AM

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

The requested operation requires elevation Windows The requested operation requires elevation Windows Jul 04, 2025 am 02:58 AM

When you encounter the prompt "This operation requires escalation of permissions", it means that you need administrator permissions to continue. Solutions include: 1. Right-click the "Run as Administrator" program or set the shortcut to always run as an administrator; 2. Check whether the current account is an administrator account, if not, switch or request administrator assistance; 3. Use administrator permissions to open a command prompt or PowerShell to execute relevant commands; 4. Bypass the restrictions by obtaining file ownership or modifying the registry when necessary, but such operations need to be cautious and fully understand the risks. Confirm permission identity and try the above methods usually solve the problem.

How to handle File Uploads securely in PHP? How to handle File Uploads securely in PHP? Jul 08, 2025 am 02:37 AM

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

How Do You Pass Variables by Value vs. by Reference in PHP? How Do You Pass Variables by Value vs. by Reference in PHP? Jul 08, 2025 am 02:42 AM

InPHP,variablesarepassedbyvaluebydefault,meaningfunctionsorassignmentsreceiveacopyofthedata,whilepassingbyreferenceallowsmodificationstoaffecttheoriginalvariable.1.Whenpassingbyvalue,changestothecopydonotimpacttheoriginal,asshownwhenassigning$b=$aorp

PHP find the position of the last occurrence of a substring PHP find the position of the last occurrence of a substring Jul 09, 2025 am 02:49 AM

The most direct way to find the last occurrence of a substring in PHP is to use the strrpos() function. 1. Use strrpos() function to directly obtain the index of the last occurrence of the substring in the main string. If it is not found, it returns false. The syntax is strrpos($haystack,$needle,$offset=0). 2. If you need to ignore case, you can use the strripos() function to implement case-insensitive search. 3. For multi-byte characters such as Chinese, the mb_strrpos() function in the mbstring extension should be used to ensure that the character position is returned instead of the byte position. 4. Note that strrpos() returns f

PHP header location ajax call not working PHP header location ajax call not working Jul 10, 2025 pm 01:46 PM

The reason why header('Location:...') in AJAX request is invalid is that the browser will not automatically perform page redirects. Because in the AJAX request, the 302 status code and Location header information returned by the server will be processed as response data, rather than triggering the jump behavior. Solutions are: 1. Return JSON data in PHP and include a jump URL; 2. Check the redirect field in the front-end AJAX callback and jump manually with window.location.href; 3. Ensure that the PHP output is only JSON to avoid parsing failure; 4. To deal with cross-domain problems, you need to set appropriate CORS headers; 5. To prevent cache interference, you can add a timestamp or set cache:f

How do I create a basic route in Yii? How do I create a basic route in Yii? Jul 09, 2025 am 01:15 AM

TocreateabasicrouteinYii,firstsetupacontrollerbyplacingitinthecontrollersdirectorywithpropernamingandclassdefinitionextendingyii\web\Controller.1)Createanactionwithinthecontrollerbydefiningapublicmethodstartingwith"action".2)ConfigureURLstr

See all articles