Albertobeiz

Albertobeiz

Symfony Tips #08 - Flush in an Event Subscriber

Symfony Tips #08 - Flush in an Event Subscriber

Subscribe to my newsletter and never miss my upcoming articles

🖥 Symfony Tips: Quick and practical tricks to develop solid backend systems.

To remove the EntityManagerInterface and any other database related code from our Use Case we will use another Symfony EventSubscriber.

This is OK

public function __invoke(Request $request):  User | Response
{
    .
    .
    .
    $this->userRepository->persist($user);
    $this->entityManager->flush();
    .
    .
    .
}

This is better

public function __invoke(Request $request):  User | Response
{
    .
    .
    .
    $this->userRepository->persist($user);
    .
    .
    .
}
class OnView_Flush implements EventSubscriberInterface
{
    public function __construct(
        private EntityManagerInterface $entityManager
    )
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            KernelEvents::VIEW => 'onView'
        ];
    }

    public function onView() {
        $this->entityManager->flush();
    }
}

Why?

flush() is a database level operation and we want our Use Case to speak business.

This solution will call flush even if we don't do any database operation but it's a good tradeoff and the performance degradation is almost inexistent.

We are almost there! We have to deal with error messages (it's http and, guess what, http is not business code 😛) and we're ready to test it.

You can re-run test.sh to see that everything keeps working.

Symfony tip completed 👍! Check the final code and leave a ⭐️!

Next Tip -> Symfony Tips #09 - Catch exceptions in an Event Subscriber

Previous Tip -> Symfony Tips #07 - Serialize output in an Event Subscriber

HEY! Follow me at @albertobeiz if you found this tip useful or have any question.

Interested in reading more such articles from Alberto Beiz?

Support the author by donating an amount of your choice.

 
Share this