• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Yii 2.0有关页面缓存方法讲解

php 搞代码 3年前 (2022-01-22) 16次浏览 已收录 0个评论

页面缓存指的是在服务器端缓存整个页面的内容。随后当同一个页面 被请求时,内容将从缓存中取出,而不是重新生成。下面这篇文章主要给大家介绍了关于Yii2.0如何使用页面缓存的相关资料,需要的朋友可以参考下。

前言

本文主要给大家介绍的是关于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, <div>本文来*源gaodai^.ma#com搞#代!码网</div><pre>搞gaodaima代码

$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 2.0有关页面缓存方法讲解的详细内容,更多请关注搞代码gaodaima其它相关文章!


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Yii 2.0有关页面缓存方法讲解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址