Reputation: 403
I have a parent (Signup) and child (Participant) entity. When I delete the last child of the parent, I want to delete the parent as well. It makes sense to me to use the postRemove lifecycle event for this, but I can find no way to access the entity manager from the entity (nor am I sure I should). What would be the proper way to accomplish this?
Upvotes: 1
Views: 391
Reputation: 5478
No, you shouldn't access EntityManager from Entity, that is fundamentally wrong.
The first option I see is triggering an event in postRemove
of your Participant
.
Then use an event subscriber, which gets injected with EntityManager
and does the work.
You may attach either participant or signup as event parameter, whatever suits you best.
EDIT: actually, I was wrong to use Symfony's event dispatcher/subscriber, but rather use Doctrine's event listeners / subscribers. When using Symfony's events, you'd still have to inject dispatcher into entity. Besides, Doctrine already emits an event, and duplicating it would be messy.
The trick is to register the listener as a service, and tag it as doctrine.event_listener
. That way, you get the access to the entity being removed via event object, and entity manager via injection, and everything is done outside of the entity. More info at Symfony cookbook
Upvotes: 2