


Introduction to some advanced usage of caching in PHP's Yii framework, phpyii framework caching_PHP tutorial
Jul 12, 2016 am 08:55 AMIntroduction 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 當(dāng)前處理的操作對象 * @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 當(dāng)前處理的操作對象 * @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

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)

Hot Topics

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
