Reputation: 1280
Context
Imagine I have a Railway network: Station
are linked together by Rail
.
Maintenance
Entity).Station
Entity can be destroyed by setting the destructionDate
attribute to something different than NULL.Stations
, defined in the Entity Rail
Station
has been connected/disconnected to which Station
and when, so in my Rail
Entity I have a connectionDate
and a disconnectionDate
attribute.What I want to do
$rail->setDisconnectionDate(now())
), the corresponding Maintenance
Entities are deleted.$station->setDestructionDate(now())
), the corresponding Rail
s are disconnected (i.e. $rail->setDisconnectionDate($station->getDestructionDate
) AND the corresponding Maintenance
Entities are deleted.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
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