Alexander Schranz
Alexander Schranz

Reputation: 2458

Restore Doctrine connection after failed flush

When a entityManager does a flush and this flush throws an exception. The doctrine entity manager will catch this exception clear the unit of work and mark the connection as closed and then doing the rollback (https://github.com/doctrine/doctrine2/blob/v2.5.6/lib/Doctrine/ORM/UnitOfWork.php#L412-L417).

I need to restore the connection but as there is no method with does $this->closed = false in the entityManager I'm confused how to handle this that after a failed flush I can flush another entity to mark this to mark in the database a specific task as failed! Also I can not run multiple tasks when a previous one failed the other can not run when when using the entityManager.

TL;DR So what is the best practice to restore the connection after a failed flush? As I see it is just marked as closed and is still connected but I dont want to use something dirty like Reflection or an custom entity manager to restore my connection.

Upvotes: 0

Views: 8487

Answers (2)

rescobar
rescobar

Reputation: 1305

Try this, first, catch in your method if it throws an exception, after that, you could check if the connection is still open, otherwise, redefine it.

 $result = $this->functionABC();// catch if it throws an exception

 $oEntityManager = $this->getContainer()->get('doctrine')->getManager();
 $bEntityManagerIsOpen = $oEntityManager->isOpen();
 if (!$bEntityManagerIsOpen) {
     $this->getContainer()->get('doctrine')->resetManager();
     $oEntityManager = $this->getContainer()->get('doctrine')->getManager();
 }

I have used this way in a Command using Symfony2.8 and it works properly for me.

Upvotes: 2

Barkati.med
Barkati.med

Reputation: 630

You can use the Function resetManager Like This $this->getDoctrine()->resetManager()
more detail in this link

edit

lets say Exemple its a table has a date field As DateTime and not null

    $Exemple = new Exemple();
    $Exemple->setDate(null);
    $em = $this->getDoctrine()->getManager();
    try {
        $em->persist($Exemple);
        $em->flush();
    } catch (\Exception $ex) {
        $em = $this->getDoctrine()->resetManager();
    }
    $Exemple->setDate(new \DateTime());
    $em->persist($Exemple);
    $em->flush();

whith $this->getDoctrine()->resetManager(); the data its flushed in database
without $this->getDoctrine()->resetManager(); we get The EntityManager is closed.

Upvotes: 3

Related Questions