Member-only story

Symfony Messenger pre and post-handle messages

Smaine Milianni
4 min readOct 2, 2022

--

👋 Symfony comes with a lot of useful tools and powerful components, one of which is Messenger.

📚 Messenger allows you to dispatch a message and consume it a/synchronously, put simply you create an object that holds data and a handler to perform your logic with those data.

💡You can use it to perform an asynchronous operation, you push your message in a broker like rabbitMQ then it will be pulled and consumed by a handler, you can also use messenger to implement the CQRS pattern.

In this article I’ll show how you can do some operations before and after a specific message is handled. It can be helpful if you have to do some action for a given message such as validating or updating the message, you may also want to do some fun stuff after the message is handled such as log information…

🍿Demo time!

1️⃣ Start the app

symfony new try_messenger --webapp

2️⃣ Create the controller, the message, and the handler

3️⃣ Configure messenger

# config/packages/messenger.yaml
framework:
messenger:
transports:
# For simplicity I configure the thransport to synchronous
sync: 'sync://'

4️⃣ Try it 👀

🎉 In a few lines of code we are able to send a message MyMessage that will be consumed by MyMessageHandler. Obviously, you should populate your message with your data, here it’s purely basic for the demo.

🗣 Now, suppose you want to perform some action before and after an instance of MyMessage is dispatched and consumed.

To do this, I will add 2 interfaces, PreHandlerInterface and PostHandlerInterface.

--

--

Smaine Milianni
Smaine Milianni

Written by Smaine Milianni

Engineering Manager- Technical Lead - certified Symfony 7,6,5,4 and certified AWS Solution Architect - Remote Worker

Responses (2)