Cache Context Drupal 8 — Part 2

Rohit Joshi
2 min readMar 10, 2017

--

In article Cache Context — Part 1, we talked about what cache context is and what are different type of cache context available in Drupal core. Here we will create a custom cache context because we are Drupal developers and we love to write code or say customize things :).

Problem statement — A site stores the user’s favorite color. For simplicity, we assume that the favorite color information will be stored in user profile with a text select list. Client wants to show the current user’s favorite color in a block with proper caching for it.

Solution — We will create a block that will show the user’s favorite color and a custom cache context based on user’s favorite color. To create a cache context, we need to register a service with tag ‘cache.context’ in container.

This will register a new cache context user_favorite_color to the Drupal. Important thing is the service name. Not like other normal services, cache context service name needs to be in specific format otherwise it will not work and that’s the case I banged my head for 2–3 hours why my custom context didn’t work.

The service name must prefix with cache_context and then your cache context name in this case it will be user_favorite_color and thus the service name is ‘cache_context.user_favorite_color’. Difficult part is done. Then we just implement this cache context class.

We need to implement the CacheContextInterface (or any base class) and implement its methods. getLabel() method just provides description of the cache context. getCachebaleMetaData() is used to add any other cacheable metadata if we want/require. The magic method is getContext() which contains the actual logic of our variation. It simply returns the string and on the basis of this string, different cache variations gets created.

Now we have created our custom cache context and now we gonna use it. For this we have created a custom block which will show the favorite color of the current user (see above code).

UserFavoriteColorBlock::build() method is just used for what needs to be rendered. Important here is the UserFavoriteColorBlock::getCacheContext(). Here we are merging our custom cache context (user_favorite_color) with the existing one so that we don’t just override the existing info.

We can check/verify if the context has added or not in chrome’s dev tool -

If you don’t want to dirty your hands in creating all these files (for cache context), you can use Drupal Console to generate that for you. All you have to do it just run command and follow the instructions in the command.

$ drupal generate:cache:context

--

--