Konstantin Myakshin
Contributed by Konstantin Myakshin in #31334

UPDATE: this feature was finally removed from Symfony before Symfony 4.4 release. Instead, DoctrineBundle now does the same thing as explained in this blog post but without you having to configure anything.


In the Messenger component, middleware is used to configure what happens when you dispatch a message to a message bus. In Symfony 4.4 we've added a new middleware to clear Doctrine's entity manager after each message is consumed.

Enable it by adding messenger.middleware.doctrine_clear_entity_manager to the middleware of your buses:

1
2
3
4
5
6
7
8
9
# config/packages/messenger.yaml
framework:
    messenger:
        buses:
            messenger.bus.default:
                default_middleware: false
                middleware:
                    # ...
                    - 'doctrine_clear_entity_manager'

The first advantage of this middleware is that it reduces the memory consumption when handling messages in long-running processes. The second advantage is that it prevents unexpected side-effects. For example, in the case of an user account recovery process (where an email is sent asynchronously with Messenger and AMQP), if the email address is updated after the first try, the second email is sent to the old email address. Using this middleware will solve that problem.

Published in #Living on the edge