Blacksad
Blacksad

Reputation: 1280

Do something when an Entity's attribute is modified

Context

Imagine I have a Railway network: Station are linked together by Rail.

What I want to do

How to solve that

For the moment, I trigger events in my controllers' Actions and it works fine. But the problem is that they are many ways in my application to disconnect 2 Stations or destroy a Station and not all of hen go through the Controller. I need to be sure not to miss a Station destruction or a Rail disconnection.

So I was thinking about trigger event in the Entity, for example in the setDestructionDate() method. I search the web and apparently this is not a good idea.

I wanted to use Doctrine postUpdate events, but they are triggered even if the destructionDate is not modified. I could filter it but I'm not sure this is the best thing to do.

So, how would you solve that problem? What is the best practice in this case?

Upvotes: 0

Views: 138

Answers (1)

bratek
bratek

Reputation: 493

you could create EventSubscriber and listen to either preUpdate or onFlush event. in preUpdate you have access to what has changed.

for example:

class YourEventListener implements EventSubscriber {

    public function getSubscribedEvents()
    {
        return array(
            Events::preUpdate => 'preUpdate'
        );
    }

    public function preUpdate(PreUpdateEventArgs $eventArgs){
        $entity = $eventArgs->getEntity();
        $em = $eventArgs->getEntityManager();

        if($entity instanceof Rail){
            if($eventArgs->hasChangedField('disconnectionDate')){
                //do something
            }
        }
    }
}

Upvotes: 2

Related Questions