The Messenger Component

The Messenger Component

The Messenger component helps applications send and receive messages to/from other applications or via message queues.

The component is greatly inspired by Matthias Noback’s series of blog posts about command buses and the SimpleBus project.

See also

This article explains how to use the Messenger features as an independent component in any PHP application. Read the Messenger: Sync & Queued Message Handling article to learn about how to use it in Symfony applications.

Installation

  1. $ composer require symfony/messenger

Note

If you install this component outside of a Symfony application, you must require the vendor/autoload.php file in your code to enable the class autoloading mechanism provided by Composer. Read this article for more details.

Concepts

Sender:

Responsible for serializing and sending messages to something. This something can be a message broker or a third party API for example.

Receiver:

Responsible for retrieving, deserializing and forwarding messages to handler(s). This can be a message queue puller or an API endpoint for example.

Handler:

Responsible for handling messages using the business logic applicable to the messages. Handlers are called by the HandleMessageMiddleware middleware.

Middleware:

Middleware can access the message and its wrapper (the envelope) while it is dispatched through the bus. Literally “the software in the middle”, those are not about core concerns (business logic) of an application. Instead, they are cross cutting concerns applicable throughout the application and affecting the entire message bus. For instance: logging, validating a message, starting a transaction, … They are also responsible for calling the next middleware in the chain, which means they can tweak the envelope, by adding stamps to it or even replacing it, as well as interrupt the middleware chain. Middleware are called both when a message is originally dispatched and again later when a message is received from a transport.

Envelope:

Messenger specific concept, it gives full flexibility inside the message bus, by wrapping the messages into it, allowing to add useful information inside through envelope stamps.

Envelope Stamps:

Piece of information you need to attach to your message: serializer context to use for transport, markers identifying a received message or any sort of metadata your middleware or transport layer may use.

Bus

The bus is used to dispatch messages. The behavior of the bus is in its ordered middleware stack. The component comes with a set of middleware that you can use.

When using the message bus with Symfony’s FrameworkBundle, the following middleware are configured for you:

  1. Symfony\Component\Messenger\Middleware\LoggingMiddleware (logs the processing of your messages)
  2. Symfony\Component\Messenger\Middleware\SendMessageMiddleware (enables asynchronous processing)
  3. Symfony\Component\Messenger\Middleware\HandleMessageMiddleware (calls the registered handler(s))

Deprecated since version 4.3: The LoggingMiddleware is deprecated since Symfony 4.3 and will be removed in 5.0. Pass a logger to SendMessageMiddleware instead.

Example:

  1. use App\Message\MyMessage;
  2. use App\MessageHandler\MyMessageHandler;
  3. use Symfony\Component\Messenger\Handler\HandlersLocator;
  4. use Symfony\Component\Messenger\MessageBus;
  5. use Symfony\Component\Messenger\Middleware\HandleMessageMiddleware;
  6. $handler = new MyMessageHandler();
  7. $bus = new MessageBus([
  8. new HandleMessageMiddleware(new HandlersLocator([
  9. MyMessage::class => [$handler],
  10. ])),
  11. ]);
  12. $bus->dispatch(new MyMessage(/* ... */));

Note

Every middleware needs to implement the Symfony\Component\Messenger\Middleware\MiddlewareInterface.

Handlers

Once dispatched to the bus, messages will be handled by a “message handler”. A message handler is a PHP callable (i.e. a function or an instance of a class) that will do the required processing for your message:

  1. namespace App\MessageHandler;
  2. use App\Message\MyMessage;
  3. class MyMessageHandler
  4. {
  5. public function __invoke(MyMessage $message)
  6. {
  7. // Message processing...
  8. }
  9. }

Adding Metadata to Messages (Envelopes)

If you need to add metadata or some configuration to a message, wrap it with the Symfony\Component\Messenger\Envelope class and add stamps. For example, to set the serialization groups used when the message goes through the transport layer, use the SerializerStamp stamp:

  1. use Symfony\Component\Messenger\Envelope;
  2. use Symfony\Component\Messenger\Stamp\SerializerStamp;
  3. $bus->dispatch(
  4. (new Envelope($message))->with(new SerializerStamp([
  5. // groups are applied to the whole message, so make sure
  6. // to define the group for every embedded object
  7. 'groups' => ['my_serialization_groups'],
  8. ]))
  9. );

Here are some important envelope stamps that are shipped with the Symfony Messenger:

  1. Symfony\Component\Messenger\Stamp\DelayStamp, to delay handling of an asynchronous message.
  2. Symfony\Component\Messenger\Stamp\DispatchAfterCurrentBusStamp, to make the message be handled after the current bus has executed. Read more at Transactional Messages: Handle New Messages After Handling is Done.
  3. Symfony\Component\Messenger\Stamp\HandledStamp, a stamp that marks the message as handled by a specific handler. Allows accessing the handler returned value and the handler name.
  4. Symfony\Component\Messenger\Stamp\ReceivedStamp, an internal stamp that marks the message as received from a transport.
  5. Symfony\Component\Messenger\Stamp\SentStamp, a stamp that marks the message as sent by a specific sender. Allows accessing the sender FQCN and the alias if available from the Symfony\Component\Messenger\Transport\Sender\SendersLocator.
  6. Symfony\Component\Messenger\Stamp\SerializerStamp, to configure the serialization groups used by the transport.
  7. Symfony\Component\Messenger\Stamp\ValidationStamp, to configure the validation groups used when the validation middleware is enabled.

Instead of dealing directly with the messages in the middleware you receive the envelope. Hence you can inspect the envelope content and its stamps, or add any:

  1. use App\Message\Stamp\AnotherStamp;
  2. use Symfony\Component\Messenger\Envelope;
  3. use Symfony\Component\Messenger\Middleware\MiddlewareInterface;
  4. use Symfony\Component\Messenger\Middleware\StackInterface;
  5. use Symfony\Component\Messenger\Stamp\ReceivedStamp;
  6. class MyOwnMiddleware implements MiddlewareInterface
  7. {
  8. public function handle(Envelope $envelope, StackInterface $stack): Envelope
  9. {
  10. if (null !== $envelope->last(ReceivedStamp::class)) {
  11. // Message just has been received...
  12. // You could for example add another stamp.
  13. $envelope = $envelope->with(new AnotherStamp(/* ... */));
  14. } else {
  15. // Message was just originally dispatched
  16. }
  17. return $stack->next()->handle($envelope, $stack);
  18. }
  19. }

The above example will forward the message to the next middleware with an additional stamp if the message has just been received (i.e. has at least one ReceivedStamp stamp). You can create your own stamps by implementing Symfony\Component\Messenger\Stamp\StampInterface.

If you want to examine all stamps on an envelope, use the $envelope->all() method, which returns all stamps grouped by type (FQCN). Alternatively, you can iterate through all stamps of a specific type by using the FQCN as first parameter of this method (e.g.$envelope->all(ReceivedStamp::class)).

Note

Any stamp must be serializable using the Symfony Serializer component if going through transport using the Symfony\Component\Messenger\Transport\Serialization\Serializer base serializer.

Transports

In order to send and receive messages, you will have to configure a transport. A transport will be responsible for communicating with your message broker or 3rd parties.

Your own Sender

Imagine that you already have an ImportantAction message going through the message bus and being handled by a handler. Now, you also want to send this message as an email (using the Mime and Mailer components).

Using the Symfony\Component\Messenger\Transport\Sender\SenderInterface, you can create your own message sender:

  1. namespace App\MessageSender;
  2. use App\Message\ImportantAction;
  3. use Symfony\Component\Mailer\MailerInterface;
  4. use Symfony\Component\Messenger\Envelope;
  5. use Symfony\Component\Messenger\Transport\Sender\SenderInterface;
  6. use Symfony\Component\Mime\Email;
  7. class ImportantActionToEmailSender implements SenderInterface
  8. {
  9. private $mailer;
  10. private $toEmail;
  11. public function __construct(MailerInterface $mailer, string $toEmail)
  12. {
  13. $this->mailer = $mailer;
  14. $this->toEmail = $toEmail;
  15. }
  16. public function send(Envelope $envelope): Envelope
  17. {
  18. $message = $envelope->getMessage();
  19. if (!$message instanceof ImportantAction) {
  20. throw new \InvalidArgumentException(sprintf('This transport only supports "%s" messages.', ImportantAction::class));
  21. }
  22. $this->mailer->send(
  23. (new Email())
  24. ->to($this->toEmail)
  25. ->subject('Important action made')
  26. ->html('<h1>Important action</h1><p>Made by '.$message->getUsername().'</p>')
  27. );
  28. return $envelope;
  29. }
  30. }

Your own Receiver

A receiver is responsible for getting messages from a source and dispatching them to the application.

Imagine you already processed some “orders” in your application using a NewOrder message. Now you want to integrate with a 3rd party or a legacy application but you can’t use an API and need to use a shared CSV file with new orders.

You will read this CSV file and dispatch a NewOrder message. All you need to do is to write your own CSV receiver:

  1. namespace App\MessageReceiver;
  2. use App\Message\NewOrder;
  3. use Symfony\Component\Messenger\Envelope;
  4. use Symfony\Component\Messenger\Exception\MessageDecodingFailedException;
  5. use Symfony\Component\Messenger\Transport\Receiver\ReceiverInterface;
  6. use Symfony\Component\Serializer\SerializerInterface;
  7. class NewOrdersFromCsvFileReceiver implements ReceiverInterface
  8. {
  9. private $serializer;
  10. private $filePath;
  11. public function __construct(SerializerInterface $serializer, string $filePath)
  12. {
  13. $this->serializer = $serializer;
  14. $this->filePath = $filePath;
  15. }
  16. public function get(): iterable
  17. {
  18. // Receive the envelope according to your transport ($yourEnvelope here),
  19. // in most cases, using a connection is the easiest solution.
  20. if (null === $yourEnvelope) {
  21. return [];
  22. }
  23. try {
  24. $envelope = $this->serializer->decode([
  25. 'body' => $yourEnvelope['body'],
  26. 'headers' => $yourEnvelope['headers'],
  27. ]);
  28. } catch (MessageDecodingFailedException $exception) {
  29. $this->connection->reject($yourEnvelope['id']);
  30. throw $exception;
  31. }
  32. return [$envelope->with(new CustomStamp($yourEnvelope['id']))];
  33. }
  34. public function ack(Envelope $envelope): void
  35. {
  36. // Add information about the handled message
  37. }
  38. public function reject(Envelope $envelope): void
  39. {
  40. // In the case of a custom connection
  41. $this->connection->reject($this->findCustomStamp($envelope)->getId());
  42. }
  43. }

New in version 4.3: In Symfony 4.3, the ReceiverInterface has changed its methods as shown in the example above. You may need to update your code if you used this interface in previous Symfony versions.

Receiver and Sender on the same Bus

To allow sending and receiving messages on the same bus and prevent an infinite loop, the message bus will add a Symfony\Component\Messenger\Stamp\ReceivedStamp stamp to the message envelopes and the Symfony\Component\Messenger\Middleware\SendMessageMiddleware middleware will know it should not route these messages again to a transport.

Learn more

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.