Background
I'm creating a render array that is built for a specific user, from data related to that user. The resulting render array is dependent on the user ID that is passed in, and it will be rendered in a block.
The resulting block will be built and shown to the user whose data it is. However, it could also be shown to privileged users via another page, where they select a user from an Entity Autocomplete dropdown and click "view" to view that user's data result.
Problem: How to Cache It
I'm having some trouble understanding the proper usage of cache tags and cache context for my use-case. My current understanding is that the cache tags should be set for the data sources the result is built from, so that if one changes, the cache is invalidated. Say the result shows that a webform has been submitted by the user, so the built data should have the cache tag ['webform_submission_list:WEBFORM_ID']
.
I don't know, though, if the cache should have user
as a cache context, or as a cache tag. The data is certainly specific to a single user, but it's not necessarily the current user. The information I viewed about cache contexts seems to indicate to me that the user
context means that the data varies based on the current user, not just a specified user.
Is that right, and if so, would the best way to cache it be to create the render array and then use something like this, not using a cache context?
// Cache ID contains the user's ID.
$cid = "my_module:data:$uid";
// Return if cached.
if ($cache = $this->cacheBackend->get($cid)) {
return $cache->data;
}
// Build the data, cache it, and return.
$data = $this->build($uid);
$this->cacheBackend->set($cid, $data, time() + $data->getCacheMaxAge(), $data->getCacheTags());
return $data;