Answer the question
In order to leave comments, you need to log in
How to cache with dependency?
Hello. I've been scratching my head for 3 hours, maybe you can help ...
And so, we cache the data through FileCache.
What do we have? A page that accepts get parameters: id, page. The getHtml function is called on the page and generates HTML code, then displays it on the page. It is necessary to cache those pages that were opened by the tag.
So that in the end I could delete the cache from key -> ID, and everything that key -> ID, PAGE deleted on their own.
That's what he did. But it is not deleted along the chain ...
public function getHtmlCache($id, $page)
{
if(!$this->site->cached) {
return $this->getHtml($id, $page);
}
$cache = Yii::createObject([
'class' => 'yii\caching\FileCache',
'cachePath' => '@common/runtime/cache/'
]);
$page = $page ?? 0;
$cache_key = [
'method' => 'API',
'type' => 'html',
'id' => $id
];
if($cache->exists($cache_key) && Yii::$app->request->get('del')) {
return $cache->delete($cache_key);
}
if($page > 0) {
$cache_key['page'] = $page;
}
$data = $cache->get($cache_key);
if($data === false) {
$data = $this->getHtml($id, $page);
$cache->set($cache_key, $data, null, new TagDependency(['tags' => 'api_site_id' . $id]));
}
return $data;
}
Answer the question
In order to leave comments, you need to log in
For caching, there are ready-made mechanisms in yii, you invent a bicycle. In addition, the mechanisms are different, for data caching, for page caching, for request caching. At the same time, there are also ready-made dependencies. Everything is in the documentation:
www.yiiframework.com/doc-2.0/guide-caching-overvie...
But specifically on caching the whole http request: www.yiiframework.com/doc-2.0/guide-caching-http.html
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question