I am developing my first Symfony 4 application and I migrating from Symfony 2+ and symfony 3+.
Right now I am developing a back-end and all of my entity classes have a addedBy()
and updatedBy()
methods where I need to record the current logged in administrator.
I would like to have something like an event listener where I do not have to set those methods in all of my controllers.
How to accomplish this?
You probably do not want to reinvent the wheel. There is the Blameable Doctrine Extension that already does that. You can install it with :
As there is already a recipe to configure it. Then you can activate the extension and then use it with something like :
Specific documentation for the Blameable extension can be found here
First, to simplify matters and help down the road I would create an interface this user-tracking entities would need to comply with:
Then you can create a Doctrine event listener, and inject the
Security
component there:You'd need to tag the listener appropriately, so it triggers on
prePersist
andpreUpdate
:While the above should work, I believe it's generally not such a great idea to use Doctrine events this way, since you are coupling your domain logic with Doctrine, and are hiding changing under a layer of magic that may not be immediately evident for other developers working with your application.
I'd put the
createdBy
as a constructor parameter, and setupdateBy
explicitly when needed. It's just one line of code each time, but you gain clarity and expressiveness, and you have a simpler system with less moving parts.This expresses much better what's happening with the domain, and future coders in your application do no have to dig around for the possible extensions you may have installed and enabled, or what events are being triggered.