Chapter 10: Caching

This chapter is part of the Drupal Module Developer Guide.

In this chapter we’ll revisit the code written in previous chapters and use Drupal’s Cache API to make it more efficient. You’ll learn important caching-related terminology like cache tags, context, and keys. And how to implement caching of both rendered content and time-consuming logic.

Tutorials in this course
Categories
Drupal 8, 9, and 10
More information

Caching is an essential piece of website performance and user experience. Drupal's Cache API enables you as a module developer to specify cacheability information for data rendered through the Render API. By storing previously calculated data or page renderings, Drupal can skip complex backend processes for subsequent requests and deliver content faster. Drupal's Cache API provides services to store, retrieve, and invalidate cached data.

In this tutorial, we'll:

  • Learn why caching is important.
  • Cover key terms and concepts associated with the Cache API.
  • Explore how and when custom modules can implement caching.

By the end of this tutorial, you should understand the core features of Drupal's Cache API and when to use them.

More information

We can enhance our site's performance by using Drupal's cache backend service to cache and reuse results from an external API request. We can cache the results of weather forecast API queries within a custom service. This will give us an opportunity to practice implementing Drupal's caching capabilities and optimize the performance of our module.

In this tutorial, we'll:

  • Inject the cache backend service into our forecast API service class.
  • Implement caching to store and reuse weather forecast API results locally.

By the end of this tutorial, you'll understand how to use Drupal's cache backend service for data caching.

More information

Whenever your custom code outputs a render array, you need to use the #cache property to define the cacheability of the content. This includes providing information about any related context that informs Drupal about how the content varies, and tags that help Drupal know what circumstances might require the cached data to be invalidated. We can add #cache properties to the render arrays output by both the custom block, and the weather page controller, to ensure they are properly cached.

In this tutorial, we'll:

  • Learn how to use the #cache property of a render array to provide cacheability data to Drupal.
  • Provide context about the data that's being displayed.
  • Tell Drupal about any dependencies of the content.

By the end of this tutorial you should be able to use the #cache property to define the cacheability of the content contained in a render array.

This course appears in the following guides:
Module Development
Learn Drupal module development in this hands-on guide.

Drupal Module Developer Guide