Messenger
| A message class | |
| A handler | |
| Sync transport first | |
| Async later |
A message class
A message is a simple object that describes work to be done, such as generating a report with a given id. It holds data only and contains no processing logic.
Name messages with verbs that reveal intent and keep properties typed so invalid payloads fail early. Small focused messages are easier to queue, log, and retry.
namespace App\Message; class SendReport { public function __construct(public int $reportId) { } }
A handler
A handler is the class that does the work described by one message type. It implements the handler interface and performs the task inside the invoke method.
Keep one handler per message so each job has a single clear owner. Throw on failure when a retry makes sense, and return normally when the work is complete.
namespace App\Handler; use App\Message\SendReport; use Symfony\Component\Messenger\Handler\MessageHandlerInterface; class SendReportHandler implements MessageHandlerInterface { public function __invoke(SendReport $message): void { echo $message->reportId; } }
Sync transport first
The sync transport runs handlers immediately in the same request, which makes development and testing simple. Dispatch the message through the bus interface wherever the work is requested.
Start every feature in sync mode so errors appear at once with a full stack trace. Move to queue based processing only after the handler logic is stable.
namespace App\Controller; use App\Message\SendReport; use Symfony\Component\Messenger\MessageBusInterface; class ReportController { public function create(MessageBusInterface $bus): void { $bus->dispatch(new SendReport(7)); } }
Async later
Async mode stores the message in a transport and processes it later with a worker process. The application code does not change because dispatching looks the same in both modes.
Switch the transport setting once the handler is ready for background work. Run a worker beside the web server so queued messages are consumed without blocking responses.
framework: messenger: transports: async: sync://
Next: Mailer
Article author: Arthur Isaev