Brief introduction to some of the cache's advanced usage _php techniques in the YII framework of PHP

Source: Internet
Author: User
Tags yii

Page Caching
page caching refers to the content of the entire page that is cached on the server side. Then, when the same page is requested, the content is taken out of the cache, not regenerated.

Page caching is supported by the Yii\filters\pagecache class, which is a filter. It can be used like this in the Controller class:

Public function behaviors ()
{return
 [
  [
   ' class ' => ' Yii\filters\pagecache '],
   ' only ' => [' Index '],
   ' duration ' =>,
   ' variations ' => [
    \yii:: $app->language,
   ],
   ' dependency ' = > [
    ' class ' => ' yii\caching\dbdependency ', '
    sql ' => ' SELECT COUNT (*) from post ',
   ],
  ],
 ];
}

The above code indicates that the page cache is enabled only at the index operation, and the page content is cached for up to 60 seconds, changing as the current application's language changes. Cached pages are invalidated if the total number of articles changes.

As you can see, page caching and fragment caching are extremely similar. They all support duration,dependencies,variations and enabled configuration options. The main difference is that the page cache is implemented by the filter, and fragment caching is a widget.

You can use fragment caching and dynamic content while using page caching.

HTTP Cache

In addition to server-side caching, WEB applications can use client caching to conserve the generation and transmission time of the same page content.

By configuring the Yii\filters\httpcache filter, the controller can manipulate the rendered content to ease the presence of the client. The Yii\filters\httpcache filter only takes effect on get and head requests, and it can set three cache-related HTTP headers for these requests.

    • Yii\filters\httpcache::lastmodified
    • Yii\filters\httpcache::etagseed
    • Yii\filters\httpcache::cachecontrolheader

Last-modified Head

The last-modified header uses a timestamp to indicate whether the page has been modified since the last client cache.

Sends a last-modified header to the client by configuring the Yii\filters\httpcache::lastmodified property. The value of this property should be the PHP callable type, which returns the Unix timestamp when the page is modified. The parameters and return values for the callable should be as follows:

/**
 * @param action $action The current processing object
 * @param array $params The value of the "params" Property
 * @return The Unix timestamp when the integer page was modified 
   */
function ($action, $params)

The following is an example of 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 preceding code indicates that the HTTP cache is enabled only when the index operation. It generates a last-modified HTTP header based on the last modification time of the page. When the browser accesses the index page for the first time, the server generates the page and sends it to the client browser. The client browser then accesses the page while the page is not modified, and the server will not regenerate the page, and the browser will use the content previously cached by the client. Therefore, both service-side rendering and content transfer will be omitted.

ETag Head

"Entity Tag" (Entity label, Short ETAG) uses a hash value to represent the page content. If the page has been modified, the hash value will change as well. By comparing the hash value of the client with the hash value generated by the server, the browser can determine whether the page has been modified, and then decide whether the content should be retransmitted.

Sends a ETAG header to the client by configuring the Yii\filters\httpcache::etagseed property. The value of this property should be the PHP callable type, and a seed character is returned to generate the ETag hash value. The parameters and return values for the callable should be as follows:

/**
 * @param action $action The Action object currently being processed
 * @param array $params The value of the "params" Property
 * @return string A seed character is used to generate the ETAG hash Value
 *
/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 preceding code indicates that the HTTP cache is enabled only when the view operation. It generates a ETAG HTTP header based on the user's requested title and content. When the browser accesses the view page for the first time, the server generates the page and sends it to the client browser. After the client browser title and content have not been modified to access the page during the period, the server will not regenerate the page, and the browser will use the content previously cached by the client. Therefore, both service-side rendering and content transfer will be omitted.

ETag can achieve more complex and accurate caching strategies than last-modified. For example, ETag can be invalidated when a site is switched to another topic.

Complex Etag generation of seeds can violate the original intent of using httpcache and incur unnecessary performance overhead because the response to each request requires a recalculation of the Etag. Try to find the simplest expression to trigger the Etag failure.

Note: To follow the 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 Head

The Cache-control header specifies the general caching policy for the page. You can send the appropriate header information by configuring the Yii\filters\httpcache::cachecontrolheader property. The following headers are sent by default:

Cache-control:public, max-age=3600

Session cache Limiter

When the page makes session, PHP will follow PHP. INI automatically sends some cache-related HTTP headers for the Session.cache_limiter value set in the These HTTP headers may interfere with your original set of HttpCache or invalidate them. To avoid this problem, HttpCache is prevented from automatically sending these headers by default. To change this behavior, you can configure the Yii\filters\httpcache::sessioncachelimiter property. This property accepts a string value, including Public,private,private_no_expire, and NoCache. Refer to the cache limiter in the PHP manual to see what these values mean.

SEO Impact

Search engines tend to follow the site's cache headers. Because some spiders have a limited crawl frequency, enabling cache headers can reduce the number of duplicate requests and increase the crawler's crawl efficiency (translator: to the effect, but the search engine ranking rules do not understand, good caching strategy should be able to add points for the user experience).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.