Table of Contents
简介PHP的Yii框架中缓存的一些高级用法,phpyii框架缓存
您可能感兴趣的文章:
Home php教程 php手册 简介PHP的Yii框架中缓存的一些高级用法,phpyii框架缓存

简介PHP的Yii框架中缓存的一些高级用法,phpyii框架缓存

Jun 13, 2016 am 08:42 AM
php yii cache

简介PHP的Yii框架中缓存的一些高级用法,phpyii框架缓存

页面缓存
页面缓存指的是在服务器端缓存整个页面的内容。随后当同一个页面被请求时,内容将从缓存中取出,而不是重新生成。

页面缓存由 yii\filters\PageCache 类提供支持,该类是一个过滤器。它可以像这样在控制器类中使用:

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',
   ],
  ],
 ];
}
Copy after login

上述代码表示页面缓存只在 index 操作时启用,页面内容最多被缓存 60 秒,会随着当前应用的语言更改而变化。如果文章总数发生变化则缓存的页面会失效。

如你所见,页面缓存和片段缓存极其相似。它们都支持 duration,dependencies,variations 和 enabled 配置选项。它们的主要区别是页面缓存是由过滤器实现,而片段缓存则是一个小部件。

你可以在使用页面缓存的同时,使用片段缓存和动态内容。

HTTP 缓存

除了服务器端缓存外, Web 应用还可以利用客户端缓存去节省相同页面内容的生成和传输时间。

通过配置 yii\filters\HttpCache 过滤器,控制器操作渲染的内容就能缓存在客户端。yii\filters\HttpCache 过滤器仅对 GET 和 HEAD 请求生效,它能为这些请求设置三种与缓存有关的 HTTP 头。

  • yii\filters\HttpCache::lastModified
  • yii\filters\HttpCache::etagSeed
  • yii\filters\HttpCache::cacheControlHeader

Last-Modified 头

Last-Modified 头使用时间戳标明页面自上次客户端缓存后是否被修改过。

通过配置 yii\filters\HttpCache::lastModified 属性向客户端发送 Last-Modified 头。该属性的值应该为 PHP callable 类型,返回的是页面修改时的 Unix 时间戳。该 callable 的参数和返回值应该如下:

/**
 * @param Action $action 当前处理的操作对象
 * @param array $params “params” 属性的值
 * @return integer 页面修改时的 Unix 时间戳
 */
function ($action, $params)
Copy after login

以下是使用 Last-Modified 头的示例:

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');
   },
  ],
 ];
}
Copy after login

上述代码表明 HTTP 缓存只在 index 操作时启用。它会基于页面最后修改时间生成一个 Last-Modified HTTP 头。当浏览器第一次访问 index 页时,服务器将会生成页面并发送至客户端浏览器。之后客户端浏览器在页面没被修改期间访问该页,服务器将不会重新生成页面,浏览器会使用之前客户端缓存下来的内容。因此服务端渲染和内容传输都将省去。

ETag 头

“Entity Tag”(实体标签,简称 ETag)使用一个哈希值表示页面内容。如果页面被修改过,哈希值也会随之改变。通过对比客户端的哈希值和服务器端生成的哈希值,浏览器就能判断页面是否被修改过,进而决定是否应该重新传输内容。

通过配置 yii\filters\HttpCache::etagSeed 属性向客户端发送 ETag 头。该属性的值应该为 PHP callable 类型,返回的是一段种子字符用来生成 ETag 哈希值。该 callable 的参数和返回值应该如下:

/**
 * @param Action $action 当前处理的操作对象
 * @param array $params “params” 属性的值
 * @return string 一段种子字符用来生成 ETag 哈希值
 */
function ($action, $params)
Copy after login

以下是使用 ETag 头的示例:

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]);
   },
  ],
 ];
}
Copy after login

上述代码表明 HTTP 缓存只在 view 操作时启用。它会基于用户请求的标题和内容生成一个 ETag HTTP 头。当浏览器第一次访问 view 页时,服务器将会生成页面并发送至客户端浏览器。之后客户端浏览器标题和内容没被修改在期间访问该页,服务器将不会重新生成页面,浏览器会使用之前客户端缓存下来的内容。因此服务端渲染和内容传输都将省去。

ETag 相比 Last-Modified 能实现更复杂和更精确的缓存策略。例如,当站点切换到另一个主题时可以使 ETag 失效。

复杂的 Etag 生成种子可能会违背使用 HttpCache 的初衷而引起不必要的性能开销,因为响应每一次请求都需要重新计算 Etag。请试着找出一个最简单的表达式去触发 Etag 失效。

注意:为了遵循 RFC 7232(HTTP 1.1 协议),如果同时配置了 ETag 和 Last-Modified 头,HttpCache 将会同时发送它们。并且如果客户端同时发送 If-None-Match 头和 If-Modified-Since 头,则只有前者会被接受。
Cache-Control 头

Cache-Control 头指定了页面的常规缓存策略。可以通过配置 yii\filters\HttpCache::cacheControlHeader 属性发送相应的头信息。默认发送以下头:

Cache-Control: public, max-age=3600
Copy after login

会话缓存限制器

当页面使 session 时,PHP 将会按照 PHP.INI 中所设置的 session.cache_limiter 值自动发送一些缓存相关的 HTTP 头。这些 HTTP 头有可能会干扰你原本设置的 HttpCache 或让其失效。为了避免此问题,默认情况下 HttpCache 禁止自动发送这些头。想改变这一行为,可以配置 yii\filters\HttpCache::sessionCacheLimiter 属性。该属性接受一个字符串值,包括 public,private,private_no_expire,和 nocache。请参考 PHP 手册中的缓存限制器了解这些值的含义。

SEO 影响

搜索引擎趋向于遵循站点的缓存头。因为一些爬虫的抓取频率有限制,启用缓存头可以可以减少重复请求数量,增加爬虫抓取效率(译者:大意如此,但搜索引擎的排名规则不了解,好的缓存策略应该是可以为用户体验加分的)。

 

您可能感兴趣的文章:

  • 详解PHP的Yii框架中自带的前端资源包的使用
  • 深入解析PHP的Yii框架中的缓存功能
  • PHP的Yii框架中View视图的使用进阶
  • PHP的Yii框架中创建视图和渲染视图的方法详解
  • PHP的Yii框架中Model模型的学习教程
  • 详解PHP的Yii框架中的Controller控制器
  • PHP的Yii框架中移除组件所绑定的行为的方法
  • PHP的Yii框架中行为的定义与绑定方法讲解
  • 深入讲解PHP的Yii框架中的属性(Property)
  • 详解PHP的Yii框架中扩展的安装与使用
Statement of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

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.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles