2

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 ...)

Community
  • 1
  • 1
Vasily
  • 1,858
  • 1
  • 21
  • 34

1 Answers1

2

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).

Tomsgu
  • 1,016
  • 1
  • 11
  • 31
  • Yes, but it's not so fit me now, cause I have a log manager service which can be used throughout all the application, not just in these handlers. And I have almost the same situation (except that I use postFlush) that you have suggested, and it had worked well till I added this very logging in preRemove handler which brought me to the situation that I have no id of removing object in *pre*Flush operation. So I looking for some more independent way of safe logging ( when I would can use this logger in any place of the application ). – Vasily Oct 09 '15 at 20:10
  • Is it the one possible variant of doing this? What do you think about one more em? – Vasily Oct 09 '15 at 20:10
  • I am not sure if I understand well. In **onFlush** (not postFlush neither preFlush) you can get all entities that are going to be inserted, deleted or updated. You have also id of entity that will be removed. – Tomsgu Oct 09 '15 at 21:33