March 28, 2018 Javier Eguiluz

In Symfony 4.1, we added a new Messenger component that helps applications send and receive messages to/from other applications or via message queues. It provides a message bus and some routing capabilities to send messages in any service where you need it, like in a controller:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 // src/Controller/DefaultController.php namespace App\Controller ; use Symfony\Bundle\FrameworkBundle\Controller\Controller ; use Symfony\Component\Messenger\MessageBusInterface ; use Symfony\Component\Routing\Annotation\Route ; class DefaultController extends Controller { /** * @Route("/", name="homepage") */ public function index ( MessageBusInterface $bus ) { // ... $bus -> dispatch ( new MyMessage ()); } }

Sending messages is the first part of the process. Then you need to create a "message handler" and register it as a service with the messenger.message_handler tag to receive the message and do something with it:

1 2 3 4 5 6 7 8 9 10 // src/MessageHandler/MyMessageHandler.php namespace App\MessageHandler ; class MyMessageHandler { public function __invoke ( MyMessage $message ) { // do something with the message } }

Queues and AMQP adapters¶ The component includes an AMQP adapter ready to communicate with most of the popular AMQP brokers, such as RabbitMQ. The communication with queuing systems or third parties (Kafka, Amazon SQS, Google Pub/sub) is delegated to libraries like Enqueue's adapter: 1 2 3 4 5 # config/packages/messenger.yaml framework : messenger : adapters : default : "amqp://guest: [email protected] :5672/%2f/messages" This config allows to route messages to the messenger.default_adapter and also configures a messenger.default_sender and messenger.default_receiver to be used when routing and consuming messages.