时时商务社区

标题: Yii 2.0如何使用页面缓存方法示例 [打印本页]

作者: 福多多1989    时间: 2018-2-14 05:25

            前言
本文主要给大家介绍的是关于Yii2.0如何使用页面缓存的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍。
起初使用页面缓存,发现使用于含有参数的方法存在弊端,只能缓存第一次的页面,导致后面所有不同参数的页面均显示第一次缓存页面;没有生成一个参数页面一个缓存;于是,进行了重写页面缓存。
示例代码
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'),
],
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
            
            
您可能感兴趣的文章:
  • Yii框架中memcache用法实例
  • Yii清理缓存的方法
  • YII Framework框架教程之缓存用法详解
  • Yii开启片段缓存的方法
  • Yii数据库缓存实例分析
  • 深入解析PHP的Yii框架中的缓存功能
  • 简介PHP的Yii框架中缓存的一些高级用法
  • 浅析Yii2缓存的使用
  • Yii2 assets清除缓存的方法
  • Yii配置与使用memcached缓存的方法
  • yii2缓存Caching基本用法示例
  • YII框架中使用memcache的方法详解
            




    欢迎光临 时时商务社区 (http://bbs.4435.cn/) Powered by Discuz! X3.2