Symfony Messenger: messages, handlers and queues

Symfony Messenger carries a message through a bus to its handler: the code that announces an action no longer knows who handles it, or when.

final readonly class ConfirmationDemandee { public function __construct(public int $reservationId) {} }

#[AsMessageHandler]
final class ConfirmationDemandeeHandler
{
    public function __invoke(ConfirmationDemandee $message): void
    {
        $reservation = $this->reservations->find($message->reservationId);
        // …
    }
}

// In the controller, after saving:
$bus->dispatch(new ConfirmationDemandee($reservation->getId()));

A controller that sends the confirmation itself, notifies accounting and updates an index does too much, and keeps the customer waiting. With Messenger, it dispatches a message, a class that only carries data, and a handler marked #[AsMessageHandler] takes care of it; a transport can then queue that message so a worker processes it later, without touching the code. The trap: a message read later only carries what was put in it. You put an entity's id in it, not the entity itself, and the handler reads it again when it does its work. If it receives something other than what it expects, it spins its wheels, without an error.

The exercises have you send the tavern's confirmation ravens through a bus, then fix an aviary where messages get lost without a trace.

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

In the tracks

In Practice

Related concepts

DebuggingScheduler