Problem/Motivation
API page: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21...
The documentation for the Render API overview contains the following example code demonstrating how to use #cache with a render array.
Here's an example of what a #cache property might contain:
'#cache' => [
'keys' => ['entity_view', 'node', $node->id()],
'contexts' => ['languages'],
'tags' => ['node:' . $node->id()],
'max-age' => Cache::PERMANENT,
],
I believe that this line 'tags' => ['node:' . $node->id()], should be 'tags' => $node->getCacheTags() instead. This demonstrates the best practice of using ::getCacheTags() for the entity instead of trying to memorize all possible cache tags you would need to include here.
I was personally getting hung up on trying to figure out what valid values for 'tags' would be. And I believe the answer is, I should haven't to know that because I can just use ::getCacheTags() for anything that implements \Drupal\Core\Cache\CacheableDependencyInterface
Proposed resolution
Update the code in documentation to use $node->getCacheTags() instead of the current example.
Remaining tasks
Update the docs.
API changes
None
Data model changes
None
| Comment | File | Size | Author |
|---|---|---|---|
| #5 | update_cache_example-2877480-5.patch | 509 bytes | yogeshmpawar |
| #5 | interdiff-2877480-2-5.txt | 519 bytes | yogeshmpawar |
| #2 | 2877480-2-render-api-use-getCacheTags.patch | 515 bytes | hardikpandya |
Comments
Comment #2
hardikpandya commentedAdded Patch.
Comment #3
eojthebraveHey @hardik.p thanks for taking a look at this.
You can do
'tags' => $node->getCacheTags()here. The getCacheTags method should return an array with all the appropriate tags for the entity in question. Which in this case basically works out toreturn ['node:' . $node->id()];The idea is to get people used to using getCacheTags to retrieve the list rather than trying to memorize, and then essentially hard-code a list of cache tags like the example currently does.
Comment #4
yogeshmpawarComment #5
yogeshmpawarChanges made as per comment #3.
Comment #6
pankajsachdeva commentedComment #7
pankajsachdeva commentedComment #8
vegantriathleteComment #10
michaellenahan commentedComment #11
cyberschorschComment #12
cyberschorsch@yogesh-pawar
Thank you for creating the patch! I reviewed your patch and now the documentation is more clear .
Marking RTBC
Comment #13
cyberschorschComment #16
gábor hojtsyThanks all for making sure this is correct. I agree documenting the best practice is important.
Comment #17
gábor hojtsy