首頁  >  文章  >  後端開發  >  Yii 2.0有關頁面快取方法講解

Yii 2.0有關頁面快取方法講解

巴扎黑
巴扎黑原創
2017-08-13 11:30:00934瀏覽

頁面快取指的是伺服器端快取整個頁面的內容。隨後當同一個頁面 被要求時,內容將從快取中取出,而不是重新產生。以下這篇文章主要為大家介紹了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
{
 /**
 * 参数设置,默认无参数
 * 用法:&#39;varByParam&#39; => Yii::$app->request->get(&#39;id&#39;)
 * @var string
 */
 public $varByParam = &#39;&#39;;

 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 ([&#39;cache&#39;, &#39;duration&#39;, &#39;dependency&#39;, &#39;variations&#39;] 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, &#39;cacheResponse&#39;]);
  return true;
 } else {
  $data = $this->cache->get($this->calculateCacheKey());
  if (is_array($data)) {
  $this->restoreResponse($response, $data);
  }
  $response->content = ob_get_clean();
  return false;
 }
 }
}
 ?>

#使用:


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

以上是Yii 2.0有關頁面快取方法講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn