I made my own custom cache context by creating the service which links to a class which implements CacheContextInterface
, and it seems to work, but the problem is, on page load, it doesn't seem to check if the context itself has changed. Neither the getContext() function nor the getCacheableMetadata() function runs on page load. If, for example, I go to a page that is a different route, it will run those functions for my cache context, as well as others. Also, if any cache tag on any page is invalidated, it will go to my custom cache context and update, but otherwise it will remain cached. How do I get that same invalidation goodness that different routes seem to have?
I notice, in core's core.services.yml, the cache_context.route
service depends on the current_route_match
service, which links to CurrentRouteMatch.php and depends on the request_stack
service. Which of these things is what causes Drupal to end up checking if the route has changed? I want to do this same thing for my custom cache context.
Will I have to depend on some core service, or is there something I can put in either a service definition (in the module's services.yml) or the service class itself that says it wants to be updated?
EDIT: What was happening was that I put this new context on a block which loads on the main page, and it was indeed checking the context only for logged in users (just as 4k4 said) but for anonymous users, on page load, it wasn't checking the context so it wasn't updating the block. I guess when it comes to requiring a cache context for anonymous users, it would be better to have the page invalidate more frequently, or get the content with ajax instead.