Symfony cache: get(), the callback and choosing the key

Symfony's cache keeps the result of an expensive computation under a key, so it is only redone when the key changes or the entry expires.

public function __construct(
    private readonly CacheInterface $cache,
    private readonly ClockInterface $horloge,
) {
}

public function ventsDuJour(string $contree): string
{
    // One key per region and per day: the next day, the key changes and the mage is consulted again.
    $cle = sprintf('vents-%s-%s', md5($contree), $this->horloge->now()->format('Y-m-d'));

    return $this->cache->get($cle, fn () => $this->mage->ventsDuJour($contree));
}

You get Symfony\Contracts\Cache\CacheInterface through autowiring, that is the cache.app pool. Its get() method takes a key and a callback: if the key is cached, the callback isn't called; otherwise, it computes the value, which is stored and then returned. The cache survives from one request to the next. A key refuses the characters {}()/\@:, hence the md5() on a free-form value. For a lifetime, the callback receives an ItemInterface and calls expiresAfter(). The trap is the key: too fine-grained, with the hour and minute for instance, it keeps changing and the cache never gets a hit, without any error; too broad, it serves a stale value.

The exercises have you remember the forecasts of a mage who charges for every consultation, once per region and per day; then understand, in a tavern gone haywire, why the bill is going up again.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

Service decorationDebuggingEventsDoctrine listeners