Sensio Labs Symfony Framework & Doctrine — monitoring Doctrine in different stages of data persistence with UnitOfWork function call can save headaches and “Doctrine Surprises” later

One of the most difficult challenges I encountered learning Symfony was learning the DBAL Doctrine. In the olden days, I was used to writing classes that handled data so I knew exactly what was going on. These days, you map your entity in Symfony and forms are objects and all the data in a form are now properties of classes. Simple enough, but when you were used to doing it more precisely, I found at some point some relationships didn’t connect the way I thought. You have to add each entity to each other, depending on the relationship, whether one-to-one or many-to-one, you added one entity to the other through a single setter or you added potentially multiple entities to a collection as an “Array Collection”.

Then, all the automagic stuff behind the scenes Doctrine and Symfony, with seldom writing more than “$em->persist()” if you mapped your entities to your database correctly it all just shows up in your database. Still, at some stages, it is difficult with multiple tables to track why certain data would update except for certain fields, etc. That usually was because you didn’t set up the relationship between the entities properly. Then you have to back track and recheck the relationships and I wonder sometimes at what stage in the controller’s data processing were the entities ready to insert or update?

This would help a lot, so I found a great troubleshooting method I handily keep in the dev base controller class called “unit of work listener. It works great, just inject the container, usually $this, and the entity manager, usually $em and this will basically create a report of the stage and state of your entities in the context of their data persistence. Call on this handy method any where you start losing sight of your entities and this will help you see if you missed creating a relationship or just basically restore your bearings if your controller seems to be getting more confusing.

function unitOfWorkListener($container,EntityManager $em){

  $uow = $em->getUnitOfWork();

  echo "

Is renewal? $this->isRenewal"; echo "

Scheduled for insertion:

"; foreach ($uow->getScheduledEntityInsertions() as $entity) { echo "


"; } echo "

Scheduled for updates:

"; foreach ($uow->getScheduledEntityUpdates() as $entity) { echo "


"; } }

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

Your email address will not be published. Required fields are marked *