This module is the code for the session about caching in DrupalCamp Spain 2016 (Granada).
It contains an example of the practical use of cache tags and cache contexts, along with common pitfalls and how to solve them.
This module provides a block that you can place in any region of your choosing. Once placed, the block will output the title of the first node ever created and a greeting to the current logged in user.
The different branches in the module show de development process of this simple task, and how important is to have caches in mind when you are rendering any thing in the page.
At this point we have created a block that retrieves the node we are looking for and puts the title in the page. We can see at this point that after a couple of refreshes the content of the block is cached. The problem arises when we edit the title of the node, the content of the block does not update.
At this point we realize that we need to invalidate the cache when the node is updated. For that we need to use cache tags.
The recommended way to add cacheability metadata (includes cache tags) to a render array is to use addCacheabilityDependency
. Doing that will have the effect of adding (the number 1
may vary depending on the calculated node):
$build['#cache']['tags'] = ['node:1'];
With this technique we have fixed our problem with stale caches.
At this point we want to add a greeting to the logged in user. Once that is done, we realize that two different authenticated users get the same cached results. That is not good.
We realize that we need to have different versions of the cache for the username render array depending on the user viewing the content. That is exactly what cache contexts are for. We add the cache context for the current user (in this case we add them manually for the sake of the example, although we should be following the best practices and use addCacheabilityDependency
).
Once that is done we don't have cache poisoning anymore.
This module does not provide any useful functionality, but aims to show the Render Cache subsystem's capabilities.