Decorating a Symfony service with #[AsDecorator]

Service decoration, in Symfony, slips a class between a service and the code that uses it, to change its behaviour without touching its code.

#[AsDecorator(Oracle::class)] // whoever asks for an Oracle now gets the notebook…
final class OracleEnCache implements Oracle
{
    public function __construct(
        #[AutowireDecorated] private readonly Oracle $mage, // … and the notebook gets the mage
        private readonly CacheInterface $cache,
    ) {
    }

    public function ventsDuJour(string $contree): string
    {
        return $this->cache->get('vents-'.md5($contree), fn () => $this->mage->ventsDuJour($contree));
    }
}

The decorator implements the same interface as the decorated service. #[AsDecorator] asks the container to put it in place of the original: wherever Oracle is injected, you get the decorator, and #[AutowireDecorated] passes it the original service, which it calls when it sees fit. Neither the controllers nor the decorated service know anything about it; that's how Symfony wraps its own services with tracing or caching. bin/console debug:container shows which service really answers to an id. The trap: a class that asks for the concrete class, OracleDuMage, instead of the interface. It gets the original and bypasses the decorator, without an error.

The exercises have you write Pipin's notebook, a decorator that remembers the forecasts of a mage who is paid for every consultation, without changing either the mage or the aviary's controller; then find out, in a tavern gone haywire where nothing raises an error, why the mage's bill is soaring again.

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

In the tracks

Related concepts

CacheDebuggingEventsDoctrine listeners