From 55d687ea5870ed80d3267d2185e29c5d1b5b6400 Mon Sep 17 00:00:00 2001 From: Alexandre Daubois Date: Fri, 8 Sep 2023 13:47:04 +0200 Subject: [PATCH] [Messenger] Mention `RedispatchMessage` and `RedispatchMessageHandler` --- messenger.rst | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/messenger.rst b/messenger.rst index 15d2e711af0..702b35a5f56 100644 --- a/messenger.rst +++ b/messenger.rst @@ -2605,6 +2605,54 @@ Messenger gives you a single message bus service by default. But, you can config as many as you want, creating "command", "query" or "event" buses and controlling their middleware. See :doc:`/messenger/multiple_buses`. +Redispatching a Message +----------------------- + +It may occur that you dispatch a message and for some reason, wants to +redispatch it through the same transport with the same envelope. To do so, you +can create a new +:class:`Symfony\\Component\\Messenger\\Message\\RedispatchMessage` and dispatch +it through your bus. Let's do this with the ``SmsNotification`` seen earlier:: + + // src/MessageHandler/SmsNotificationHandler.php + namespace App\MessageHandler; + + use App\Message\SmsNotification; + use Symfony\Component\Messenger\Attribute\AsMessageHandler; + use Symfony\Component\Messenger\MessageBusInterface; + use Symfony\Component\Messenger\Message\RedispatchMessage; + + #[AsMessageHandler] + class SmsNotificationHandler + { + public function __construct(private MessageBusInterface $bus) + { + } + + public function __invoke(SmsNotification $message): void + { + // do something with the message + // then redispatch it based on your own logic + + if ($needsRedispatch) { + $this->bus->dispatch(new RedispatchMessage($message)); + } + } + } + +The built-in +:class:`Symfony\\Component\\Messenger\\Handler\\RedispatchMessageHandler` will +take care of this message and redispatch it through the same bus it's been +dispatched at first. You can also use the second argument of the +``RedispatchMessage`` constructor to provide transports to use when +redispatching the message. + +.. versionadded:: 6.3 + + The :class:`Symfony\\Component\\Messenger\\Message\\RedispatchMessage` + and :class:`Symfony\\Component\\Messenger\\Handler\\RedispatchMessageHandler` + classes were introduced in Symfony 6.3. + Learn more ----------