I'm a programmer specialising in performant and scalable systems using PHP and Ruby and cooking

On Doctrine | PHP

Doctrine, Event Listeners and persisted IDs

Recently I was writing a small event listener to handle updating search indexes for object freshly persisted to the database. I am using MySQL as my backend, and because of this IDs are generated after the object has been inserted, not before.

I spent ages trying to get the id of the object so I could add this to the search index. Turns out the easiest way to do this is to listen for a Lifecycle event called PostPersist. This event is called after flushing the objects and after the object have been added to the database so the entities have their ids.

public function postPersist(LifecycleEventArgs $args)  
    $entity = $args->getEntity();

    $id = $entity->getId();

    // process entity date here

As you can see getting the ID is really very simple. Annoying it took me so long to work out and so many extensions out there seem to massively over complicate things.

Thanks to Jonathan Wage, Stuart Lowes and Florian Klein for their help on this.