Drupal send cache invalidation to Varnish on content update or delete
A client was using the Advanced Varnish module (https://www.drupal.org/project/adv_varnish) and to my surprise, there was no cache invalidation built into it.
The idea is that whenever a node is updated or deleted, a cache invalidation request is sent automatically to Varnish cache.
First, build the cache invalidation function in a custom module, in the .module file:
function [MODULE_NAME]_node_inv_varnish($node) {
// Get the URI of the current node.
$uri = $node->toUrl()->toString();
// Get the CacheManager service.
/** @var \Drupal\adv_varnish\CacheManagerInterface $cache_manager */
$cache_manager = \Drupal::service('adv_vanish.cache_manager');
// if $uri begins with '/node/' then get the alias.
if (strpos($uri, '/node/') === 0) {
$uri = \Drupal::service('path_alias.manager')->getAliasByPath($uri);
}
// Purge the URI from the Varnish cache.
$cache_manager->purgeUri($uri);
if ($node->getType() === 'news') {
// Invalidate the cache tag for the node.
$cache_manager->purgeUri('/news');
}
// Get the front page URI.
$front_page_uri = \Drupal::config('system.site')->get('page.front');
// if $uri begins with '/node/' then get the alias.
if (strpos($front_page_uri, '/node/') === 0) {
$front_page_uri = \Drupal::service('path_alias.manager')->getAliasByPath($front_page_uri);
}
if ($uri === $front_page_uri) {
// Purge the front page URI from the Varnish cache.
$cache_manager->purgeUri('/');
$cache_manager->purgeUri($front_page_uri);
// Invalidate the cache tag for the front page.
\Drupal::service('cache_tags.invalidator')->invalidateTags(['config:system.site']);
$cache_manager->purgeTags(['config:system.site']);
}
}
Then, use that function in the corresponding hooks: node_update and node_delete.
/**
* Implements hook_node_update().
*/
function [MODULE_NAME]_node_update($node) {
theme_customization_node_inv_varnish($node);
}
/**
* Implements hook_node_delete().
*/
function [MODULE_NAME]_node_delete($node) {
theme_customization_node_inv_varnish($node);
}