Home >Backend Development >PHP Tutorial >Yii 2.0 explanation of page caching methods
Page caching refers to caching the content of the entire page on the server side. Subsequently when the same page is requested, the content will be fetched from the cache rather than regenerated. The following article mainly introduces relevant information about how Yii2.0 uses page caching. Friends in need can refer to it.
Preface
This article mainly introduces to you the relevant content about how Yii2.0 uses page caching, and shares it for your reference and study. , let’s take a look at the detailed introduction.
I initially used page caching and found that the method containing parameters had drawbacks. It could only cache the first page, causing all subsequent pages with different parameters to display the first cached page; no parameter page was generated. A cache; therefore, the page cache was rewritten.
Sample Code
##
<?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; } } } ?>
Usage:
[ 'class' => 'common\lib\PageCache', 'only' => ['view'], 'duration' => 0, //永不过期 'varByParam' => Yii::$app->request->get('id'), ],
The above is the detailed content of Yii 2.0 explanation of page caching methods. For more information, please follow other related articles on the PHP Chinese website!