@scotty_walker
The Symfony Messenger component is a powerful tool for handling messages in your Symfony applications. The Messenger component provides a simple and flexible way to send and receive messages using different transports like AMQP, Redis, or even plain PHP.
To use the Symfony Messenger bundle to handle messages, follow these steps:
1
|
composer require symfony/messenger |
1 2 3 4 5 6 |
framework: messenger: transports: async: '%env(MESSENGER_TRANSPORT_DSN)%' routing: 'AppMessageMyMessage': async |
This configuration sets up a transport named async
and routes messages of type AppMessageMyMessage
to this transport. The transport is defined using an environment variable named MESSENGER_TRANSPORT_DSN
, which should contain the connection string for the transport you want to use (e.g. amqp://guest:guest@localhost:5672
for RabbitMQ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// src/Message/MyMessage.php namespace AppMessage; class MyMessage implements SymfonyComponentMessengerEnvelopeAwareInterface { private $payload; public function __construct($payload) { $this->payload = $payload; } public function getPayload() { return $this->payload; } } |
This message class has a single property named $payload
, which can be any PHP value. The getPayload()
method returns the payload value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// src/Controller/MyController.php namespace AppController; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyComponentMessengerMessageBusInterface; use AppMessageMyMessage; class MyController extends AbstractController { public function index(MessageBusInterface $bus) { $message = new MyMessage('Hello, world!'); $bus->dispatch($message); return $this->json([ 'message' => 'Message sent!', ]); } } |
This controller sends a MyMessage
object to the message bus using the dispatch()
method. The message will be routed to the async
transport defined in the configuration file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// src/MessageHandler/MyMessageHandler.php namespace AppMessageHandler; use AppMessageMyMessage; class MyMessageHandler implements SymfonyComponentMessengerHandlerMessageHandlerInterface { public function __invoke(MyMessage $message) { $payload = $message->getPayload(); // Do something with the payload... return true; } } |
This handler class has a single __invoke()
method that accepts a MyMessage
object as its argument. The method retrieves the payload value using the getPayload()
method and does something with it (e.g. store it in a database, send an email, etc.). The method must return a boolean value to indicate whether the message has been successfully handled.
1 2 |
services: AppMessageHandlerMyMessageHandler |