媒介
本文首要给各人先容的是关于Yii2.0怎样行使页面缓存的相干内容,分享出来供各人参考进修,下面来一路看看具体的先容。
早先行使页面缓存,发明行使于含有参数的要领存在破绽,只能缓存第一次的页面,导致后头全部差异参数的页面均表现第一次缓存页面;没有天生一个参数页面一个缓存;于是,举办了重写页面缓存。
示例代码
namespace commonlib;
use Yii;
use yiicachingCache;
use yiidiInstance;
use yiiwebResponse;
use yiifiltersPageCache 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;
}
}
}
?>
行使:
'commonlibPageCache','only' => ['view'],'duration' => 0,//永不外期
'varByParam' => Yii::$app->request->get('id'),],
总结
以上就是这篇文章的所有内容了,但愿本文的内容对各人的进修可能事变能带来必然的辅佐,假若有疑问各人可以留言交换,感谢各人对编程之家的支持。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|