2

I just used a cache service explicitely for the first time, in a function that calls a remote service. The result is a simple string that may change day by day, but it's very rare that it changes for the past – so I expire it at midnight.

I injected cache.default in my controller – then I saw that in core services there is also a service called cache.data. What's the difference? Is there any reason to prefer one to the other?

1 Answer 1

4

Cache bins

Cache storage is separated into "bins", each containing various cache items. Each bin can be configured separately; see Configuration.

When you request a cache object, you can specify the bin name in your call to \Drupal::cache(). Alternatively, you can request a bin by getting service "cache.nameofbin" from the container. The default bin is called default, with service name cache.default, it is used to store common and frequently used caches.

Other common cache bins are the following:

  • bootstrap: Data needed from the beginning to the end of most requests, that has a very strict limit on variations and is invalidated rarely.
  • render: Contains cached HTML strings like cached pages and blocks, can grow to large size.
  • data: Contains data that can vary by path or similar context.
  • discovery: Contains cached discovery data for things such as plugins, views_data, or YAML discovered data such as library info.

https://api.drupal.org/api/drupal/core!core.api.php/group/cache

3
  • Yeah, sorry, I had missed that – Drupal documentation can be overwhelming, sometimes :/ Commented Oct 6, 2022 at 9:19
  • And it seems that cache.default is the right choice, after all :) Commented Oct 6, 2022 at 9:19
  • One thing to notice is the DEFAULT_MAX_ROWS constant value and the configurable setting for the DatabaseBackend class that currently defaults to 5000. This could be import as garbageCollection method would delete the oldest entries that exceed that limitation. Due to this fact, it might make sense to create a custom cache bin to make sure that the cache is not seemingly randomly deleted.
    – Pjotr
    Commented Mar 6 at 16:13

Your Answer

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

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