Drupal 9 - Invalidate Cache Tags

Caching is a great way to get exceptional performance on Drupal sites. All sites should be cached. However, there are times where caching can serve users wrong data.

For example, let's say you have an event listing page, which is supposed to only display upcoming events. However, an event in the past is still displayed. An easy fix would be to "flush all caches" however this would cause your site to slow down for a brief moment in time.

A neat solution is to utilise the `invalidateCacheTags` provided by the Cache class.

Step 1:

Obtain the cache tag of the view. I suggest using a hook that provides the $view object. For example, you could use the `hook_preprocess_views_view` hook.

function hook_preprocess_views_view(&$variables) {
   * @var \Drupal\views\ViewExecutable $view .
  $view = $variables['view'];

Step 2:

From the $view variable, you can use the `getCacheTags` method. 


This would result in an array of tags used for this view. In my case I had the following values as tags for my view:

['config:search_api.index.solr', 'config:views.view.search'];

Step 3:

Now the fun part! We want to ensure that caches are invalidated for our event listing page anytime cron is run (which should be often depending on how your server is configured). We will utilise the cron hook like so:

  * Implements hook_cron().
function hook_cron() {
    $views_search_tags = ['config:search_api.index.solr', 'config:views.view.search'];


You can be rest assured using this method will display the correct data to your users and ensure the performance of your site is not affected severly.