UpVs
UpVs

Reputation: 1958

Persist object in PostPersist, PostUpdate events

I have a logger which use Doctrine to writes in DB. And I need log some events in Doctrine PostPersist, PostUpdate and PreRemove handlers of an Entity Listener.
But a flush operation is officialy unsupported (and sometimes cause fatal errors if neglect it) in these handlers.
I have encountered a similar question, but the solution is to defer a flush to the end of a currently performing flush, which is not suit me, cause I need to insert entry right in the handlers, e.g. in order not to lose object id during remove operation.
I have a LogManager and want that this add-log-entry operation be the same - no matter whether you invoke it from some handler or from some another place in code.
I wonder is there a way to persist objects in the handlers? (May be by using another EntityManager ...)

Upvotes: 2

Views: 1159

Answers (1)

Tomsgu
Tomsgu

Reputation: 1016

You can use onFlush event that I think suites well to your needs. Instead of using flush method you have to recompute/compute changes manually. See the link.

From Doctrine2 documentation:

  • If you create and persist a new entity in onFlush, then calling EntityManager#persist() is not enough. You have to execute an additional call to $unitOfWork->computeChangeSet($classMetadata, $entity).

  • Changing primitive fields or associations requires you to explicitly trigger a re-computation of the changeset of the affected entity. This can be done by calling $unitOfWork->recomputeSingleEntityChangeSet($classMetadata, $entity).

Upvotes: 2

Related Questions