Add CacheBackendRememberInterface with remember helper

Created on 12 November 2018, over 5 years ago
Updated 28 February 2024, 4 months ago

Problem/Motivation

πŸ“Œ Make cache()->get() return a classed CacheItem object Needs work will improve the return type from get a lot making it quite a bit easier to work with but handling cache misses in Drupal can be a bit complicated. Returning an object means you have to do some inspection and understand the object and the way caches behave when you you just want the caching system to help you avoid doing some costly action over and over. And lets all admit, if you haven't messed with caches in a while, you probably forget about the intermediate object the first time you prototype your code.

Proposed resolution

I suggest we add a helper that combines get/set into one handy function looking something like this:

$data = $this->cache->remember($cid, $expire, function () {
  return 'My expensive value';
});

or to steal from the core documentation is would replace most uses of this:

$cid = 'mymodule_example:' . \Drupal::languageManager()
  ->getCurrentLanguage()
  ->getId();
$data = NULL;
if ($cache = \Drupal::cache()
  ->get($cid)) {
  $data = $cache->data;
}
else {
  $data = my_module_complicated_calculation();
  \Drupal::cache()
    ->set($cid, $data);
}

with this:

$bin = \Drupal::cache();
$cid = 'mymodule_example:' . \Drupal::languageManager()
  ->getCurrentLanguage()
  ->getId();
$data = $bin->remember($cid, Cache::PERMANENT, function() {
  return my_module_complicated_calculation();
}

This idea is shamelessly stolen from Laravel's cache repository because it simplifies so much logic out of most cache uses.
https://laravel.com/api/5.4/Illuminate/Contracts/Cache/Repository.html#m...

Remaining tasks

Discuss plan and agree if its a good idea
Decide on the interface
Write implementation
CR
Update documentation

User interface changes

n/a

API changes

New API. Provided as new interface for BC but maybe merged into CacheBackendInterface for 9.x?

Data model changes

n/a

✨ Feature request
Status

Needs work

Version

11.0 πŸ”₯

Component
CacheΒ  β†’

Last updated about 11 hours ago

Created by

πŸ‡ΊπŸ‡ΈUnited States neclimdul Houston, TX

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.69.0 2024