Caching in block plugins

The render array we saw earlier was used as part of a Controller response. The latter is also known as the main content as it is the primary output of the page. On a normal Drupal installation, which uses the Block module, this is included inside the Main page content block. We also said that setting a max-age of 0 will bubble up to the top-level render array, causing the entire page to not be cached. This is true so far as the Controller response is concerned. Other blocks are still cached independently according to their own metadata.

In this book, you have already learned how we can create custom blocks, and we saw that they are also built using render arrays. Since this is the case, cache metadata can also be applied to those arrays for caching them properly. However, since we are extending from the BlockBase class when creating block plugins, we are essentially implementing the CacheableDependencyInterface because BlockPluginInterface extends it.

So instead of setting the metadata on the render array, we should, whenever possible, use the methods on that interface by overriding the default parent implementations. For example:

/** 
* {@inheritdoc} 
*/ 
public function getCacheContexts() { 
  return Cache::mergeContexts(parent::getCacheContexts(), ['user']); 
}  

We should always merge our own values with the ones from the parent.

In some cases, though, especially when declaring cache tags, it makes more sense to set them inside the render array of the build() method. That is because you may have already done some work to get your hands on the dependent objects, and it doesn't make sense to repeat that inside another method. That is totally fine.