Symfony Messenger makes it easy to send messages without worrying about how or when they are handled. Besides defining handlers, you also need to decide which transport should carry a given message. A transport can be synchronous, asynchronous, or even multiple at once. This tutorial provides 2 methods how to route Messenger message to transport in Symfony 8 application.
First, define a simple message handler that will process the SMS notification.
src/Messaging/Handler/SmsNotificationHandler.php
<?php
namespace App\Messaging\Handler;
use App\Messaging\Message\SmsNotification;
use Symfony\Component\Messenger\Attribute\AsMessageHandler;
#[AsMessageHandler]
class SmsNotificationHandler
{
public function __invoke(SmsNotification $smsNotification): void
{
echo $smsNotification->getMessage();
}
}
For testing purposes, dispatch a message from a controller using the Messenger bus. At this point, Symfony decides which transport to use based on the configuration.
src/Controller/TestController.php
<?php
namespace App\Controller;
use App\Messaging\Message\SmsNotification;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Attribute\Route;
class TestController
{
#[Route('/')]
public function index(MessageBusInterface $bus): Response
{
$smsNotification = new SmsNotification();
$smsNotification->setMessage('Hello world');
$bus->dispatch($smsNotification);
return new Response();
}
}
Method 1 - AsMessage attribute
One way to control message routing is directly on the message class itself by using the AsMessage attribute. This approach keeps routing logic close to the message definition.
config/packages/messenger.yaml
framework:
messenger:
transports:
sync: 'sync://'
src/Messaging/Message/SmsNotification.php
<?php
namespace App\Messaging\Message;
use Symfony\Component\Messenger\Attribute\AsMessage;
#[AsMessage('sync')]
class SmsNotification
{
private string $message;
public function getMessage(): string { return $this->message; }
public function setMessage(string $message): void { $this->message = $message; }
}
We can also send the same message to multiple transports if needed:
#[AsMessage(['sync', 'async'])]
Method 2 - routing option
Another common approach is defining routing rules in the Messenger configuration file using routing option. This keeps transport decisions centralized and avoids adding routing logic to message classes.
config/packages/messenger.yaml
framework:
messenger:
transports:
sync: 'sync://'
routing:
App\Messaging\Message\SmsNotification: sync
src/Messaging/Message/SmsNotification.php
<?php
namespace App\Messaging\Message;
class SmsNotification
{
private string $message;
public function getMessage(): string { return $this->message; }
public function setMessage(string $message): void { $this->message = $message; }
}
We can also route a message to multiple transports:
App\Messaging\Message\SmsNotification: [sync, async]
Leave a Comment
Cancel reply