Drupal 8 Cache API | Drupal 8

Drupal 8 Cache API

Submitted by editor on Tue, 10/25/2016 - 11:06

How to use the Drupal 8 Cache API ?

Get the default cache bin

$cache = \Drupal::cache();

To get a particular cache bin (here 'render'):

$render_cache = \Drupal::cache('render');

Save / Cache itmes
$my_object = 'A stdClass';
Drupal::cache()->set('my_cache_key', $my_object, CacheBackendInterface::CACHE_PERMANENT, array('my_first_tag', 'my_second_tag'));

Read a cached item

$cache = \Drupal::cache()->get('my_cache_key');

Cache remove and invalidation

You can remove cache manually using following methods:
invalidate(), invalidateMultiple(), invalidateAll(), delete(), deleteMultiple() or deleteAll();

And also using cache tags

Example: To invalidate cach with tags 'node:5' and/or 'my_first_tag'
\Drupal\Core\Cache\Cache::invalidateTags(array('node:5', 'my_first_tag'));

Delete Cache (by CID)

$cids = ['cid1', 'cid2',];


Cache contex


Add new comment

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.