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
- The first raven Symfony for PHP developers · chapter 7: The messenger raven
- 🐉 Boss: the broken aviary Symfony for PHP developers · chapter 7: The messenger raven
In Practice
- The shop follows the whole import, with PropagatedStampInterface A stamp implementing PropagatedStampInterface is copied onto every message sent during handling, and the handler gets it as an argument: no more context to pass from message to message.
- Pay, ship, and cancel if it breaks ChainStamp chains messages in order, and DispatchOnFailureStamp sends the cancellation whichever step fails: a saga in a single dispatch().