Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

symfony - preUpdate and postUpdate events not triggered on Doctrine 2

I have followed the instructions from this tutorial: http://symfony.com/doc/current/cookbook/doctrine/event_listeners_subscribers.html, and have created a simple listener, that listens for events dispatched by Doctrine on insert or update of an entity. The preInsert and the postInsert events work fine and are dispatched on the creation of a new entity. However, preUpdate and postUpdate are never called on the update of the entity no matter what. The same goes for onFlush. As a side note, I have a console generated controller that supports the basic CRUD operations, and have left it untouched.

Below are some code snippets to demonstrate the way I am doing this.

config.yml

annotation.listener:
    class: CityAnnotatorBundleListenerAnnotationListener
    tags:
        -  { name: doctrine.event_listener, event: postUpdate}

Listener implementation (I have omitted the other functions and left only the postUpdate for simplicity purposes)

class AnnotationListener
{

    public function postUpdate(LifecycleEventArgs $args)
    {
        $entity=$args->getEntity();

        echo $entity->getId();
        die;
    }
}

The entity id is never displayed, and the script continues its execution until it is complete, despite the die at the end of the function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Did you forget to add @HasLifecycleCallbacks annotaion? You could use @PreUpdate annotation and skip service definition altogether.

/**
 * @ORMEntity
 * @ORMHasLifecycleCallbacks
 */
class YouEntity
{

    /**
     * @ORMPrePersist()
     * @ORMPreUpdate()
     */
    public function preUpdate(){
        // .... your pre-update logic here
    }
    ....
}

In my opinion this way of attaching events is much easier as you don't have to define new services and listeners explicitly. Also you have direct access to data being updated as this method is locations within your entity.

Now, drawback is that you mix logic with your model and that's something that should be avoided if possible...

You can read more about Lifecycle callbacks here: http://symfony.com/doc/master/cookbook/doctrine/file_uploads.html#using-lifecycle-callbacks


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...