Yii 2.0如何使用页面缓存方法示例

yipeiwu_com5年前PHP代码库

前言

本文主要给大家介绍的是关于Yii2.0如何使用页面缓存的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍。

起初使用页面缓存,发现使用于含有参数的方法存在弊端,只能缓存第一次的页面,导致后面所有不同参数的页面均显示第一次缓存页面;没有生成一个参数页面一个缓存;于是,进行了重写页面缓存。

示例代码

<?php 


namespace common\lib;

use Yii;
use yii\caching\Cache;
use yii\di\Instance;
use yii\web\Response;
use yii\filters\PageCache as PCache;


/**
* 重写页面缓存,增加varByParam参数一列
*/
class PageCache extends PCache
{
 /**
 * 参数设置,默认无参数
 * 用法:'varByParam' => Yii::$app->request->get('id')
 * @var string
 */
 public $varByParam = '';

 public function beforeAction($action)
 {
 if (!$this->enabled) {
  return true;
 }

 $this->cache = Instance::ensure($this->cache, Cache::className());

 if (is_array($this->dependency)) {
  $this->dependency = Yii::createObject($this->dependency);
 }

 $properties = [];
 foreach (['cache', 'duration', 'dependency', 'variations'] as $name) {
  $properties[$name] = $this->$name;
 }
 $id = $this->varyByRoute ? $action->getUniqueId().$this->varByParam : __CLASS__;
 $response = Yii::$app->getResponse();
 ob_start();
 ob_implicit_flush(false);
 if ($this->view->beginCache($id, $properties)) {
  $response->on(Response::EVENT_AFTER_SEND, [$this, 'cacheResponse']);
  return true;
 } else {
  $data = $this->cache->get($this->calculateCacheKey());
  if (is_array($data)) {
  $this->restoreResponse($response, $data);
  }
  $response->content = ob_get_clean();
  return false;
 }
 }
}
 ?>

使用:

[
'class' => 'common\lib\PageCache',
  'only' => ['view'],
  'duration' => 0, //永不过期
  'varByParam' => Yii::$app->request->get('id'),
],

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对【宜配屋www.yipeiwu.com】的支持。

相关文章

解析php中die(),exit(),return的区别

die()停止程序运行,输出内容exit是停止程序运行,不输出内容return是返回值die是遇到错误才停止exit是直接停止,并且不运行后续代码,exit()可以显示内容。return...

使用php+Ajax实现唯一校验实现代码[简单应用]

使用php+Ajax实现唯一校验实现代码[简单应用]

首先创建一个Ajax类(Ajax类) 然后新建一个文件form.html --------------------------form.html---------------------...

PHP setcookie() cannot modify header information 的解决方法

使用setcookie()函数时总是报以下错误: Warning: Cannot modify header information - headers already sent by....

PHP文件上传类实例详解

本文实例讲述了PHP文件上传类。分享给大家供大家参考,具体如下: 这里演示了FileUpload.class.php文件上传类,其中用到了两个常量,可在网站配置文件中定义: defi...

php str_pad() 将字符串填充成指定长度的字符串

/** * 将字符串填充成指定长度的字符串(多字节安全) * @param string $str 指定被填充的字符串 * @param int $len 指定被填充的字符串的长度,如果...