Change record status: 
Project: 
Introduced in branch: 
8.x
Description: 

Changes were made to CacheBackendInterface::set() to add support for cache tags. Cache Tags can be used to flag certain cache entries which allows to invalidate them based on the used tags later on. For example, invalidate all cache entries that have been tagged with a certain node id if that node is updated.

Previously, some kind of naming scheme for the cache ID's was necessary to do that, combined with prefix based cache deleting.

$cache = cache($bin);
$nid = 1;
$cache->set('cache_nid_' . $nid . '_id_one', $some_value);
$cache->set('cache_nid_' . $nid . '_id_two', $some_value);

$cache->deletePrefix('cache_id_' . $nid);

With cache tags, it is easier to identify multiple cache entries and invalidate them later on.

$cache = cache($bin);
$nid = 1;
$cache->set('cache_id_one', $some_value, CacheBackendInterface::CACHE_PERMANENT, array('node:' . $nid));
$cache->set('cache_id_two', $some_value, CacheBackendInterface::CACHE_PERMANENT, array('node:' . $nid));

Cache::invalidateTags(array('node:' . $nid));

(Note: entities now have a getCacheTag() method, so you could do Cache::invalidateTags($node->getCacheTag()).)

Multiple cache tags per cache entry are allowed, which allows to tag a cache entry as being related to two nodes or a node and a term and then invalidate them using any of these tags. This is impossible to implement with the prefix based approach.

To clear cached HTML (currently the page, block and render caches):

// D7
cache_clear_all();

// D8
Cache::invalidateTags(array('rendered'));

CACHE_TEMPORARY has been removed. To replicate the old behavior of a temporary cache, tie it to the 'rendered' cache tag, which is used for the render cache (which includes the block and page cache).
To set cached HTML:

// D7
cache_set($cid, $data, $bin, CACHE_TEMPORARY);

// D8
cache($bin)->set($cid, $data, CacheBackendInterface::CACHE_PERMANENT, array('rendered'));

You can still set an explicit TTL using a Unix timestamp:

// D7
cache_set($cid, $data, $bin, 1542646800);

// D8
cache($bin)->set($cid, $data, 1542646800);
Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

s_leu’s picture

(Note: entities now have a getCacheTag() method, so you could do Cache::invalidateTags($node->getCacheTag()).)

Seems like nowadays the method is rather named

EntityInterface::getCacheTags()

instead