Caching access results

Another important place where cache metadata needs to be considered is on AccessResultInterface objects. If you remember from the previous chapter, objects implementing this interface are used consistently to represent access to a certain resource. On top of that, they can also contain cacheability metadata. This is because access may depend on certain data that can change with an impact on the access result itself. Since Drupal tries to cache access as well, we need to inform it of these dependencies.

A good example to see this in action is our HelloWorldAccess service where we dynamically check access to our hello_world.hello route. So instead of simply returning the AccessResultInterface, we add cacheable dependencies to it before doing so. The rewritten access() method can now look like this:

$config = $this->configFactory->get('hello_world.custom_salutation'); 
$salutation = $config->get('salutation'); 
$access = in_array('editor', $account->getRoles()) && $salutation != "" ? AccessResult::forbidden() : AccessResult::allowed(); 
$access->addCacheableDependency($config); 
$access->addCacheableDependency($account); 
return $access;  

The addCacheableDependency() method usually takes CacheableDependencyInterface objects to read their cache metadata. If something else is passed, the access result is deemed not cacheable. So in our case, since the access depends on both the salutation configuration object and the user account, we add them both as cache dependencies.