Cache API

Last updated on
13 October 2016

The Cache API is much improved in Drupal 8. The following sections go into more detail on each feature.

For a brief run-down, see also the Cache API page from the API documentation.

Cacheability metadata

All things that either are directly renderable or are used to determine what to render provide cacheability metadata — ranging from access results to entities and URLs.

Cacheability metadata consists of 3 properties:

cache tags
For dependencies on data managed by Drupal, like entities & configuration
cache contexts
For variations, i.e. dependencies on the request context
cache max-age
For time-sensitive caching, i.e. time dependencies

Practical: how you'll typically use the Cache API

Typically, your code will end up rendering things (blocks, entities, and so on) and your controllers will return render arrays or responses. So, usually, you won't be interacting with the Cache API directly. Instead you'll be using:

Render caching (aka fragment caching)
The Render API uses cacheability metadata embedded in render arrays to perform caching (aka render caching). Therefore, the Cache API should not be used to interact with the render cache (neither to retrieve cache items nor to create new ones).
See Cacheability of render arrays.
Response caching
The cacheability metadata used by the Render API (see the previous section) bubbles all the way up to Response objects (usually a HtmlResponse) that implement CacheableResponseInterface.
The cacheability metadata on these Response objects is what allows Drupal 8 to ship with Page Cache and Dynamic Page Cache enabled by default, because it allows them to work transparently: they are always up-to-date and always vary appropriately.
See CacheableResponseInterface.