4

I have a controller that serves a path, /get-messages, which requires a query argument, path. An example request to this path will look like /get-messages?path=/about/team.

I have a content type, Message. Each message has a textarea field that allows the editor to enter paths that the message should appear on. Example content:

/about/team
/about/*

With javascript, on page load, I make a request to my controller, e.g. /get-messages?path=/the/current/path, to get all messages that should be displayed on the current page.

This all works fine and is no problem. The issue I'm having is with how to cache my responses correctly.

With core's default caching options, I might setup a cache render array like:

[
  'keys' => ['my_module_get_messages'],
  'contexts' => ['url.query_args'], // or `url.query_args:path`
  'max-age' = Cache::PERMANENT,
]

I can even add any message entities as cache dependencies to make sure their cache tags get added and the cache is broken if they're edited. This also works fine.

The issue I'm having is if someone adds a new message that should display on a path that's already cached, by default, creating the new entity won't clear the cache for any already existing cache entries.

I think I need a cache tag based on my url. Is there an existing cache tag I can use, or do I need to create/manage my own custom tags (as described in Implementing Custom Cache Tags)? Or an alternative caching approach?

1 Answer 1

6

You could add a listing cache tag for the content type:

  'tags' => ['node_list:message'],

This cache tag was introduced in Drupal 8.9. See the change record Added an ENTITY_TYPE_list:BUNDLE cache tag.

1
  • Thanks, this still feels like overkill, but may be better than a custom tag.
    – sonfd
    Jan 20, 2021 at 19:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.