8

In Drupal 7, we used to be able to do this:

cache_clear_all('state:', 'cache', TRUE)

which would delete any cache bin entires that started with the string state: (matching cache IDs such as state:info and state:nebraska).

The change record at https://www.drupal.org/node/1272696 even notes this use case in the Drupal 7 example, but does not actually provide an example of how to replicate it in D8.

It seems that we're supposed to use cache tags, which seems like a more more expensive conversion considering the simple use case. I don't see any matching methods that would apply in CacheBackendInterface. Note, this is not about deleting all items in a cache bin, which is clearly covered by deleteAll().

1 Answer 1

9

Not sure why the existing answer was deleted, it was (almost) correct.

Wildcard cache clears was removed. It was extremely complicated to support in backends like redis and memcache, which have no wildcard support.

Cache tags is the replacement and it is not that complicated to use. You just pass along a list of strings as the 4th argument (a bit annoying that you have to set the default timestamp argument, a separate method would be nice):

\Drupal::cache('default')->set('state:info', $your_data, Cache::PERMANENT, 
['state']);

and then call:

\Drupal\Core\Cache\Cache::invalidateTags(array('state'));
3
  • Ok, I'll help update the change notice to be more explicit that cache tags must be used as a replacement.
    – Dave Reid
    Sep 20, 2016 at 23:41
  • What is a reliable way to get all the cache keys that need to be tagged for deletion? E.g. if I want to clear 'entity_bundle_extra_fields:node:article:' . $langcode for all languages? I could get a list of all languages, but is there something simpler? In this case it already has a cache tag, 'entity_field_info'. But maybe I want to invalidate less broad.
    – donquixote
    Aug 20, 2017 at 21:19
  • No, there is not. The cache API has no query/list method. And you shouldn't directly interact with cache entries of someone else, use the API, e.g. entity field manager clear cached definitions in this case. Those cache entries are not an API, core is free to change the keys/structure and then your code would be broken
    – Berdir
    Aug 21, 2017 at 6:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.