Symfony & Doctrine Entity Listeners
Recently, I had the need for auditing the change-set of a particular entity and recording it into another entity — which is also persisted in the database. This means that any changes made to Foo need to be saved into a FooHistory entity — which is either created/updated for the day.
Rather than find all the places in the code-base where we are updating the entity (in this case there are many controllers doing this), I thought it best that we update it right at the source — the moment before it is written to the database. Keep things simple right?
Fortunately for me, Doctrine has a nice set of events that are fired at various stages of the update process — the trouble was in getting them to play nicely with writing the changes to the database.
Here’s how I implemented it in Symfony 4.4
First, create the Event Listener in /src/AppBundle/EventListener
Then, add the service to the app/config/service.yml
What this means is that any time there is an entity update from Foo
— notify my event listener AppBundle\EventListener\FooListener
and let it do what it wants
Hope this helps someone else — there are many more complicated solutions around but I found this to be the simplest approach