search
HomeBackend DevelopmentPHP TutorialIntroduction 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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1117068.htmlTechArticleIntroduction to some advanced usage of caching in PHP's Yii framework. The phpyii framework caches the page cache. The page cache refers to the cache on the server. Cache the content of the entire page. Then when the same page is requested...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!