


Summary of the use of filters in PHP's Yii framework, yii filter_PHP tutorial
Jul 12, 2016 am 08:55 AMA 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:
<?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:
<?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)證方法的令牌。 注意為了可運(yùn)行,yii\web\User::identityClass 類必須 實(shí)現(xiàn) yii\web\IdentityInterface::findIdentityByAccessToken()方法。
use yii\filters\auth\HttpBasicAuth; public function behaviors() { return [ 'basicAuth' => [ 'class' => HttpBasicAuth::className(), ], ]; }
認(rèn)證方法過濾器通常在實(shí)現(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第一個配置項(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ù)器端整個頁面的緩存。如下示例所示,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ù) 漏桶算法 來實(shí)現(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

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

The core role of Homebrew in the construction of Mac environment is to simplify software installation and management. 1. Homebrew automatically handles dependencies and encapsulates complex compilation and installation processes into simple commands; 2. Provides a unified software package ecosystem to ensure the standardization of software installation location and configuration; 3. Integrates service management functions, and can easily start and stop services through brewservices; 4. Convenient software upgrade and maintenance, and improves system security and functionality.
