Contributed by
Konstantin Myakshin
in #31334.
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:
# ...
- 'messenger.middleware.doctrine_clear_entity_manager'
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <!-- config/packages/messenger.xml -->
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="https://symfony.com/schema/dic/services"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:framework="https://symfony.com/schema/dic/symfony"
xsi:schemaLocation="https://symfony.com/schema/dic/services
https://symfony.com/schema/dic/services/services-1.0.xsd
https://symfony.com/schema/dic/symfony
https://symfony.com/schema/dic/symfony/symfony-1.0.xsd">
<framework:config>
<framework:messenger>
<!-- ... -->
<framework:middleware id="messenger.middleware.doctrine_clear_entity_manager"/>
<framework:bus name="messenger.bus.default" default-middleware="false"/>
</framework:messenger>
</framework:config>
</container>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // config/packages/messenger.php
$container->loadFromExtension('framework', [
'messenger' => [
'buses' => [
'messenger.bus.default' => [
'middleware' => [
// ...
'messenger.middleware.doctrine_clear_entity_manager',
],
'default_middleware' => false,
],
],
],
]);
|
The first advantage of this middleware is that it avoids memory leaks during the handling of messages. The second advantage is that it prevents unexpected side-effects. For example, in the case of a 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.
What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...