


Introduction to some advanced usage of caching in PHP's Yii framework, phpyii framework caching_PHP tutorial
Introduction to some advanced usage of caching in PHP's Yii framework, phpyii framework caching
Page caching
Page caching refers to caching the content of the entire page on the server side. Subsequently when the same page is requested, the content will be fetched from the cache rather than regenerated.
Page caching is supported by the yiifiltersPageCache class, which is a filter. It can be used in a controller class like this:
public function behaviors() { return [ [ 'class' => 'yii\filters\PageCache', 'only' => ['index'], 'duration' => 60, 'variations' => [ \Yii::$app->language, ], 'dependency' => [ 'class' => 'yii\caching\DbDependency', 'sql' => 'SELECT COUNT(*) FROM post', ], ], ]; }
The above code indicates that page caching is only enabled during the index operation. The page content is cached for up to 60 seconds and will change as the language of the current application changes. If the total number of articles changes, the cached page will become invalid.
As you can see, page caching and fragment caching are very similar. They all support duration, dependencies, variations and enabled configuration options. The main difference between them is that page caching is implemented by filters, while fragment caching is a widget.
You can use fragment caching and dynamic content at the same time as page caching.
HTTP Cache
In addition to server-side caching, web applications can also use client-side caching to save time in generating and transmitting the same page content.
By configuring the yiifiltersHttpCache filter, the content rendered by the controller operation can be cached on the client. The yiifiltersHttpCache filter only takes effect on GET and HEAD requests, and it can set three cache-related HTTP headers for these requests.
- yiifiltersHttpCache::lastModified
- yiifiltersHttpCache::etagSeed
- yiifiltersHttpCache::cacheControlHeader
Last-Modified Header
The Last-Modified header uses a timestamp to indicate whether the page has been modified since the last time the client cached it.
Send the Last-Modified header to the client by configuring the yiifiltersHttpCache::lastModified property. The value of this attribute should be of PHP callable type and returns the Unix timestamp when the page was modified. The parameters and return value of this callable should be as follows:
/** * @param Action $action 当前处理的操作对象 * @param array $params “params” 属性的值 * @return integer 页面修改时的 Unix 时间戳 */ function ($action, $params)
The following is an example using the Last-Modified header:
public function behaviors() { return [ [ 'class' => 'yii\filters\HttpCache', 'only' => ['index'], 'lastModified' => function ($action, $params) { $q = new \yii\db\Query(); return $q->from('post')->max('updated_at'); }, ], ]; }
The above code indicates that HTTP caching is only enabled during index operations. It generates a Last-Modified HTTP header based on the last modified time of the page. When a browser accesses the index page for the first time, the server will generate the page and send it to the client browser. Later, when the client browser accesses the page while the page has not been modified, the server will not regenerate the page, and the browser will use the content cached by the previous client. Therefore, server-side rendering and content transmission will be omitted.
ETag header
"Entity Tag" (ETag for short) uses a hash value to represent page content. If the page has been modified, the hash value will also change. By comparing the client-side hash value with the hash value generated by the server-side, the browser can determine whether the page has been modified and decide whether the content should be retransmitted.
Send the ETag header to the client by configuring the yiifiltersHttpCache::etagSeed property. The value of this attribute should be of PHP callable type and returns a seed character used to generate the ETag hash value. The parameters and return value of this callable should be as follows:
/** * @param Action $action 当前处理的操作对象 * @param array $params “params” 属性的值 * @return string 一段种子字符用来生成 ETag 哈希值 */ function ($action, $params)
The following is an example of using the ETag header:
public function behaviors() { return [ [ 'class' => 'yii\filters\HttpCache', 'only' => ['view'], 'etagSeed' => function ($action, $params) { $post = $this->findModel(\Yii::$app->request->get('id')); return serialize([$post->title, $post->content]); }, ], ]; }
The above code indicates that HTTP caching is only enabled during view operations. It generates an ETag HTTP header based on the headers and content of the user's request. When the browser accesses the view page for the first time, the server will generate the page and send it to the client browser. Afterwards, the title and content of the client's browser have not been modified. If the page is accessed during the period, the server will not regenerate the page, and the browser will use the content cached by the previous client. Therefore, server-side rendering and content transmission will be omitted.
ETag can implement more complex and precise caching strategies than Last-Modified. For example, an ETag can be invalidated when the site switches to another theme.
Complex Etag generation seeds may defeat the original purpose of using HttpCache and cause unnecessary performance overhead, because the Etag needs to be recalculated in response to each request. Please try to find the simplest expression to trigger Etag failure.
Note: To comply with RFC 7232 (HTTP 1.1 protocol), if both ETag and Last-Modified headers are configured, HttpCache will send them at the same time. And if the client sends both the If-None-Match header and the If-Modified-Since header, only the former will be accepted.
Cache-Control header
The Cache-Control header specifies the general caching strategy for the page. The corresponding header information can be sent by configuring the yiifiltersHttpCache::cacheControlHeader property. The following headers are sent by default:
Cache-Control: public, max-age=3600
Session Cache Limiter
When the page uses session, PHP will automatically send some cache-related HTTP headers according to the session.cache_limiter value set in PHP.INI. These HTTP headers may interfere with the HttpCache you originally set or make it invalid. To avoid this problem, HttpCache disables automatic sending of these headers by default. To change this behavior, you can configure the yiifiltersHttpCache::sessionCacheLimiter property. This property accepts a string value including public, private, private_no_expire, and nocache. Please refer to Cache Limiters in the PHP manual for the meaning of these values.
SEO Impact
Search engines tend to follow a site’s cache headers. Because the crawling frequency of some crawlers is limited, enabling cache headers can reduce the number of repeated requests and increase crawler crawling efficiency. Experience is a plus).
Articles you may be interested in:
- Detailed explanation of the use of the front-end resource package that comes with PHP's Yii framework
- In-depth analysis of the caching function in PHP's Yii framework
- Advanced use of Views in PHP's Yii framework
- Detailed explanation of the methods of creating and rendering views in PHP's Yii framework
- Learning about Model models in PHP's Yii framework Tutorial
- 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
- Behavior in PHP's Yii framework Explanation of the definition and binding methods
- In-depth explanation of the properties (Property) in PHP's Yii framework
- Detailed explanation of the installation and use of extensions in PHP's Yii framework

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.
