To invalidate a cache you should use the Drupal cache invalidator service : cache_tags.invalidator
.
Static call
// Invalide a Node cache.
\Drupal::service('cache_tags.invalidator')->invalidateTags(['node:5']);
// Invalidate a custom entity cache.
\Drupal::service('cache_tags.invalidator')->invalidateTags(['custom_entity:5']);
// Invalidate a custom cache tag.
\Drupal::service('cache_tags.invalidator')->invalidateTags(['thing:identifier']);
Dependency injection call
my_module.services.yml
services:
hello.service:
class: \Drupal\my_module\Service\Hello
arguments:
- '@cache.default'
- '@cache_tags.invalidator'
Hello.php
use Drupal\Core\Cache\Cache;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Cache\CacheTagsInvalidator;
class Hello {
/**
* Cache backend.
*
* @var Drupal\Core\Cache\CacheBackendInterface
*/
protected $cacheBackend;
/**
* Cache tags invalidator.
*
* @var Drupal\Core\Cache\CacheTagsInvalidator
*/
protected $cacheInvalidator;
/**
* {@inheritdoc}
*/
public function __construct(
CacheBackendInterface $cacheBackend,
CacheTagsInvalidator $cacheInvalidator
) {
$this->cacheBackend = $cacheBackend;
$this->cacheInvalidator = $cacheInvalidator;
}
/**
* Function getting something from cache.
*/
public function getSomething() {
$cid = 'thing:identifier';
$data = NULL;
$cache = $this->cacheBackend->get($cid);
if ($cache) {
$data = $cache->data;
}
else {
$data = my_module_complicated_calculation();
$this->cacheBackend->set(
$cid, // Cache tag identifier.
$data, // Data to store in cache.
Cache::PERMANENT, // Save permanently.
['node:5', 'user:7']// Automatically invalidated if these entities are modified.
);
}
return $data;
}
/**
* Function invalidating a cache tag.
*/
public function invalidateSomething() {
$cid = 'thing:identifier';
$this->cacheInvalidator->invalidateTags([$cid]);
return;
}
}
Links