Invalidate data cache whenever any entry or category is saved #12208
-
I'm building a controller that returns some data based on a lot of entries. I want to cache the output, but invalidate the cache whenever any entry included in the query is saved, another entry is added, or a category related to any of the entries is saved. I'm fine with invalidating caches whenever any entry or category is saved or added. I've read the caching guide but I'm having a hard time figuring out how Craft uses cache tags. This is what I've got so far: /** @var \yii\caching\CacheInterface $cache */
$cache = Craft::$app->getCache();
$cacheKey = [__CLASS__, __METHOD__, 'all-offers-data'];
if ($cachedResponse = $cache->get($cacheKey)) {
return $this->asJson($cachedResponse);
}
$query = $this->getQuery();
$result = $this->process($query);
$dependency = new ElementQueryTagDependency($query);
$cache->set(
$cacheKey,
$result,
self::CACHE_DURATION,
$dependency,
); This does invalidate the cache whenever any entry in the query is saved, but not when a related category or other element is saved. I thought using more general cache tags would solve this, but I can't get it to work. I tried a couple different tags with $dependency = new TagDependency(['tags' => [
'element',
'element::' . Category::class,
'element::' . Entry::class,
]]);
$dependency = new TagDependency(['tags' => ['element']]);
$dependency = new TagDependency(['tags' => ['*']]); Is there any way to create a cache dependency that will change whenever any entry or category is saved? And is there any documentation on how those cache tags in Craft work in detail? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Here’s how you’d do it in Craft 3: // Turn on element cache tag collection
Craft::$app->elements->startCollectingCacheTags();
// Execute the query
$query = $this->getQuery();
$result = $this->process($query);
// Stop collecting cache tag collection, and get the resulting TagDependency
$dependency = Craft::$app->elements->stopCollectingCacheTags();
// Cache the results with the dependency
$cache->set($cacheKey, $result, self::CACHE_DURATION, $dependency); That will still work in Craft 4, but those two // Turn on element cache info collection
Craft::$app->elements->startCollectingCacheInfo();
// Execute the query
$query = $this->getQuery();
$result = $this->process($query);
// Stop collecting cache tag collection, and get the resulting TagDependency
[$dependency, $duration] = Craft::$app->elements->stopCollectingCacheInfo();
// Cache the results with the dependency
$cache->set($cacheKey, $result, $duration ?? self::CACHE_DURATION, $dependency); |
Beta Was this translation helpful? Give feedback.
Here’s how you’d do it in Craft 3:
That will still work in Craft 4, but those two
Elements
service methods have been deprecated in favor ofstartCollectingCacheInfo()
andstopCollectingCacheInfo()
. The advantage of the new methods is that you will get the recommended ca…