Allow modules to add their own cache tags to a specific routing cache entry

Created on 18 November 2023, 10 months ago
Updated 6 February 2024, 7 months ago

Problem/Motivation

Drupal's Routing/RouteProvider caches the association between an incoming path and matching routes (including parameters), for each request. This happens after all other processes are done and after all processInbounds.

The thing is that it only explicitly provides the route_match cache tag for all those cache entries, in getRouteCollectionForRequest(Request $request), which doesn't make it possible to implement more selective cache invalidations in case you want the cache to expire only for a particular path/route.

$this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']);

Proposed resolution

Provide a hook to allow modules to add their own cache tags for a specific path/route, based on the $request.

I'm providing a patch that introduces hook_routing_cache_tags(Request $request).

Example:

/**
 * Allow modules to add their own cache tags to the routing cache object.
 *
 * RouteProvider stores the association of paths and routes in the cache.
 * It only adds the generic tag 'route_match'. Modules can implement this hook
 * to add more tags, based on the `$request`, in order to perform more
 * selective cache invalidations.
 */
function hook_routing_cache_tags(Request $request) {
  if ($request->getPathInfo() == 'some_path' || $request->attributes->get('some_attribute')) {
    return [
      'custom_tag:1',
      'custom_tag:2',
      'custom_tag:3',
    ];
  }
}

Then, in your module, you invalidate the tags added to those specific paths:

Cache::invalidateTags(['custom_tag:1']);

✨ Feature request
Status

Needs work

Version

11.0 πŸ”₯

Component
RoutingΒ  β†’

Last updated 8 days ago

Created by

πŸ‡¨πŸ‡΄Colombia camilo.escobar

Live updates comments and jobs are added and updated live.
  • Needs subsystem maintainer review

    It is used to alert the maintainer(s) of a particular core subsystem that an issue significantly impacts their subsystem, and their signoff is needed (see the governance policy draft for more information). Also, if you use this tag, make sure the issue component is set to the correct subsystem. If an issue significantly impacts more than one subsystem, use needs framework manager review instead.

  • Needs tests

    The change is currently missing an automated test that fails when run with the original code, and succeeds when the bug has been fixed.

  • Needs issue summary update

    Issue summaries save everyone time if they are kept up-to-date. See Update issue summary task instructions.

Sign in to follow issues

Comments & Activities

Production build 0.71.5 2024