Home >Backend Development >PHP Tutorial >Introduction to some advanced usage of caching in PHP's Yii framework, phpyii framework caching_PHP tutorial
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.
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).