BentCoder
BentCoder

Reputation: 12730

Very simple example of event listener on preUpdate() event of an object hangs/fails

Event Listener example below works fine for prePersist() and postPersist() however browser times out for preUpdate() and postUpdate(). Anyone knows why this is happening?

Note: Event listener is the one which cause problem because controller works fine when used on its own. I checked the database.

Error:

Maximum execution time of 30 seconds exceeded in /var/www/html/local/listener/vendor/doctrine/orm/lib/Doctrine/ORM/UnitOfWork.php line 685

Event listener

class UserListener
{
    //public function postUpdate(LifecycleEventArgs $args)
    public function preUpdate(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();

        if ($entity instanceof User) {
            $userLog = new UserLog();
            $userLog->setDescription('User Update.');

            $em = $args->getEntityManager();
            $em->persist($userLog);
            $em->flush();
        }
    }
}

Controller:

public function updateUser()
{
    $repo = $this->getDoctrine()->getRepository('SiteFrontBundle:User');
    $user = $repo->findOneBy(array('id' => 1));
    $user->setLock(true);

    $em = $this->getDoctrine()->getManager();
    $em->flush();
}

Service.yml

services:

    entity.event_listener.user:
        class:  Site\FrontBundle\EventListener\Entity\UserListener
        tags:
            - { name: doctrine.event_listener, event: preUpdate }

Upvotes: 0

Views: 1791

Answers (1)

Cerad
Cerad

Reputation: 48865

preUpdate is very limited.

From: http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#preupdate

Any calls to EntityManager#persist() or EntityManager#remove(), 
even in combination with the UnitOfWork API are strongly discouraged and 
don’t work as expected outside the flush operation.

Probably need to use onFlush, http://doctrine-orm.readthedocs.org/en/latest/reference/events.html#onflush

Might also want to take look at how these guys do it: https://github.com/Atlantic18/DoctrineExtensions/tree/master/lib/Gedmo/Loggable

Or just setup a logging entity manager.

Upvotes: 1

Related Questions