Doctrine middleware do not make flush

552 Views Asked by At

My config/messanger.yaml looks like:

framework:
    messenger:
        default_bus: command.bus
        buses:
            command.bus:
                middleware: 'Symfony\Bridge\Doctrine\Messenger\DoctrineTransactionMiddleware'
            query.bus: ~

And the command handler for command UpdateUser looks like this:

final class UpdateUserHandler implements CommandHandlerInterface
{
    /**
     * @var Users
     */
    private Users $users;

    public function __construct(Users $users)
    {
        $this->users = $users;
    }

    public function __invoke(UpdateUser $command)
    {
        $user = $command->getUser();
        $user->setName($command->getName());
    }

And now I am dispatching this command from the controller:

final class UserController extends AbstractController
{
    private CommandBus $commandBus;

    public function __construct(CommandBus $commandBus)
    {
        $this->commandBus = $commandBus;
    }

    public function __invoke(Request $request, User $user): Response
    {
        $this->commandBus->dispatch(new UpdateUser($user, $name));

        return $this->render('user.html.twig', []);
    }
}

Could you tell me why automatic flush on middleware DoctrineTransactionMiddleware does not work? What I am missing?

1

There are 1 best solutions below

1
On
final class UpdateUserHandler implements CommandHandlerInterface
{
/**
 * @var Users
 */
private Users $users;

private EntityManagerInterface $em;


public function __construct(Users $users, EntityManagerInterface $em)
{
    $this->users = $users;
    $this->em = $em;
}

public function __invoke(UpdateUser $command)
{
    $user = $command->getUser();
    $user->setName($command->getName());
    $this->em->flush();
}

}

Better call flush method explicitly.