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
Example:
$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',];
\Drupal::cache()->delete($cids);
Cache contex
https://www.drupal.org/docs/8/api/cache-api/cache-contexts
Comments