Doctrine listeners in Symfony: acting before an entity is saved

A Doctrine listener, in Symfony, reacts to an entity's life cycle, before it is inserted or updated, whatever code saves it.

#[AsEntityListener(event: Events::prePersist, method: 'prePersist', entity: Plat::class)]
final class SlugDuPlat
{
    public function __construct(private readonly SluggerInterface $slugger)
    {
    }

    public function prePersist(Plat $plat, PrePersistEventArgs $args): void
    {
        if (null !== $plat->getSlug()) {
            return; // a hand-picked slug is kept
        }
        $plat->setSlug($this->slugger->slug((string) $plat->getNom())->lower()->toString());
    }
}

A computation placed in a controller only applies to that controller; commands, fixtures and tests forget it. Doctrine announces what it does itself, prePersist, preUpdate, postRemove, and #[AsEntityListener] plugs a service into one event and one specific entity class. The $args argument gives access to the entity manager, getObjectManager(), for instance to check that a slug isn't already taken. The trap: a listener that overwrites unconditionally. Recomputing the slug on every insert also replaces the hand-picked ones, and addresses already shared answer 404, without any error saying so.

The exercises have you write the listener that gives every new dish a slug taken from its name, without accents or duplicates, then, in a tavern turned upside down by Pipin, find out why the links to the stew shared by the bards lead to a 404.

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

In the tracks

Related concepts

DebuggingEventsService decorationCache