Check Access and Cache
Route access checkers, hook_entity_access()
, and anything that is expected to return an AccessResultInterface
object must add appropriate cacheability metadata.
If you haven’t yet, read about cache tags, cache contexts, and max-age.
Access Check Parameters
The access checker will receive various parameters — at minimum, a user account (AccountInterface
) and often an object. It will then make decisions based on the properties of those parameters.
A cacheable dependency on $parameter
must be added if changing any property of this parameter would alter the access result.
For example:
$access_result = AccessResult::allowedIf($node->isPublished()) // Access result depends on a property of the object that might change: it is a cacheable dependency. ->addCacheableDependency($node);
Another common case is when the access result depends on a property that cannot change (usually an ID or UUID). For example, allowing access if the given user account is the owner of the object:
$access_result = AccessResult::allowedIf($node->getOwnerId() === $account->id()) // Access result depends on the node's owner, the owner might change. ->addCacheableDependency($node); // Access result also depends on a user account, and the ID of the user account can never change. Hence we don't need to add $account as a cacheable dependency. // But, if $account is the current user, and not some hardcoded user, we also need to make sure we vary this by the current user, so that we don't run this access check once and then reuse its result for all users. if ($account->id() === \Drupal::currentUser()->id()) { $access_result->cachePerUser(); }
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.