The documentation on render array caching (https://www.drupal.org/developing/api/8/render/arrays/cacheability) seems to say that caching can be set on a render array at any level.

Currently, we're setting it on the whole entity using hook_entity_build_defaults_alter(). If we could instead set it on just the render array for the flag link, then we'd remove a whole hook implementation, and save a fair amount of legwork, since hook_entity_build_defaults_alter() basically repeats the work of hook_entity_view() ('which flags apply to this entity? are any of them displayed? what is their current state?').

I'm guessing that Drupal core's render array caching system will bubble up the cache settings, and possibly the end-result is the same: the whole entity gets the cache settings that we set on the flag link, which make it per-user. But then we'd be relying on core to do this, rather than doing it ourselves, so if in the future core can do something to split the caching into the per-user bits and the global bits (or if contrib comes along and caters for that), then we benefit automatically.

I don't know if this is going to work, but I'm going to post a patch to see if this idea passes tests :)

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

joachim’s picture

Status: Active » Needs review
FileSize
1.66 KB

Status: Needs review » Needs work

The last submitted patch, 1: 2475505-1.flag_.cache-settings-on-link.patch, failed testing.

Berdir’s picture

I explained in #2473921-10: FlagSimpleTest is failing due to render/page caching why this doesn't work.

You can set contexts and tags on any level, but not cache keys. Those need to exist *before* doing the cache get.

We could theoretically make the information a cache context, but that only works through cache redirection and needs multiple cache gets, which makes it slower.

It's either the hook or a post render callback and since we need to go with a post render callback anyway for the link csrf tokens, this is won't fix :)

joachim’s picture

> You can set contexts and tags on any level, but not cache keys. Those need to exist *before* doing the cache get.

Sorry if this is a stupid question, but does that mean we could just add an extra level in the render array?

We potentially need one anyway, as currently we're missing a wrapper around the flag link: #2461107: Flag links output as fields need to be in a block-level element.

joachim’s picture

Status: Needs work » Closed (won't fix)