You probably already know about Doctrine events. What could you do:
Use the postPersist event postPersist . This happens after inserting the database, so automatically generated identifiers are available.
The EventManager class can help you with this:
class MyEventListener { public function postPersist(LifecycleEventArgs $eventArgs) { // in a listener you have the entity instance and the // EntityManager available via the event arguments $entity = $eventArgs->getEntity(); $em = $eventArgs->getEntityManager(); if ($entity instanceof User) { // do some stuff } } } $eventManager = $em->getEventManager(): $eventManager->addEventListener(Events::postPersist, new MyEventListener());
Be sure to check e. d. if User already has Image , otherwise, if you call a flash in the event listener, you may end up in an infinite loop.
Of course, you can also make your User class aware of this operation of creating an image with an inline postPersist eventHandler and add @HasLifecycleCallbacks to your mapping and then always paint over at the end of the e request. d. in the shutdown function, but, in my opinion, this type of material belongs to an individual listener. YMMV.
If you need an identifier for an object before cleaning, immediately after creating the object, another approach is to create identifiers for objects inside your application, e. d. using uuids .
Now you can do something like:
class Entity { public function __construct() { $this->id = uuid_create(); } }
Now you already have the identifier set when you just do:
$e = new Entity();
And you only need to call EntityManager :: flush at the end of the request
source share