In my custom module, I define a custom block that performs an expensive operation:
/**
* {@inheritdoc}
*/
public function build() {
$data = get_expensive_data();
$agent_number = get_agent_number_from_context();
return [
'#theme' => 'my_custom_module',
'#cache' => [
'keys' => ['my_block', 'full_version', $agent_number],
'tags' => ['my_custom_module'],
'max-age' => 86400,
],
];
}
The caching works except when another user views the block or a user with a different role view the page; it creates a new cache item. Is it possible to have cache only one time for multiple users/roles?
Edit
I tried the following (ended up using route
context just to not add another variable to my problem):
/**
* {@inheritdoc}
*/
public function build() {
$data = get_expensive_data();
return [
'#theme' => 'my_custom_module',
'#data' => $data,
'#cache' => [
'contexts' => ['route'],
'tags' => ['my_module'],
'max-age' => 86400,
],
];
}
Noticed when I had the block using Layout Builder via Page Manager, no item got added to the cache_render
table (that might be a separate issue). When I added the block on default Drupal Block Layout I noticed that it still created a new cache record for every user. For example:
User 1 navigated to: /my-account/A123 and the following record got added to the cache_render
table:
cid
entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=1
tags
block_view config:block.block.mycustomblock config:user.role.administrator config:user.role.authenticated my_module rendered user:1
User 72 navigated to: /my-account/A123 and the following record got added to the cache_render
table:
cid
entity_view:block:mycustomblock:[languages:language_interface]=en:[route]=entity.node.canonical7ccb4f15749b8c9e759f0016bfc863bd5e6bef88ea0a9dfe7b1cbe2687d30b32:[theme]=my_theme:[url.site]=http://mysite.test:[user]=79
tags
block_view config:block.block.mycustomblock config:user.role.agent config:user.role.authenticated my_module rendered user:79
With using contexts, I am still seeing it create a new record for every user.
Edit 3
I think my test form Edit 2 is invalid because I was trying to make the block work outside of page manager but I needed the context from page manager so it was using the logged-in users. Long story short, I need to figure out why context caching isn't working (although key caching is working) when using Page Manager or Layout Manager.
max-age
doesn't work for anonymous users (anonymous user role). See Limitations of max-age