Cache API
The Cache API has been significantly improved in Drupal 8. The following sections explore each feature in more detail.
For a quick overview, see the Cache API documentation page.
Cacheability Metadata
Everything that is rendered directly or used to determine what to render provides cacheability metadata — from access results to entities and URLs.
Cacheability metadata consists of three properties:
- Cache tags
Used for data dependencies managed by Drupal, such as entities and configuration.
- Cache contexts
Used for variants, i.e., dependencies on the request context.
- Cache max-age
Used for time-sensitive caching, i.e., time-based dependencies.
Practical Use: How You Typically Use the Cache API
Typically, your code ends with rendering objects (blocks, entities, etc.), and your controllers return render arrays or responses. Therefore, you usually won’t interact directly with the Cache API. Instead, you will use:
Render Caching (also known as Fragment Caching)
The render API uses cacheability metadata embedded in render arrays to perform caching (or rendering). So the Cache API should not be used to interact with the render cache directly (neither retrieving cache items nor creating new ones).
See Cacheability of render arrays.
Response Caching
The cacheability metadata used by the render API (see previous section) bubbles all the way up to the Response objects (usually HtmlResponse
), which implement the CacheableResponseInterface
.
The metadata in these Response objects allows Drupal 8 to ship with Page Cache and Dynamic Page Cache enabled by default, as they can work transparently: they always stay up-to-date and vary appropriately.
See CacheableResponseInterface.
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.