首页 > PHP教程 > php开发知识文章

php -- Yii2框架页面缓存的使用方法

页面缓存指的是在服务器端缓存整个页面的内容。随后当同一个页面 被请求时,内容将从缓存中取出,而不是重新生成。

本文主要介绍了php -- Yii2框架页面缓存的使用方法,需要的朋友参考下。

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'),
]

php -- Yii2框架页面缓存的使用方法

以上就是本文php -- Yii2框架页面缓存的使用方法的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,谢谢大家对本站的支持。

关闭
感谢您的支持,我会继续努力!
扫码打赏,建议金额1-10元


提醒:打赏金额将直接进入对方账号,无法退款,请您谨慎操作。