Doctrine postLoad event for associations

I currently have an object that I would modify a bit at boot time. This modification will be a one-time change, which will then be saved in a new field along with the entity.

To clarify my current goal: the object is a "location" and is part of a nested set. It has a name, lft / rgt values, and an identifier. One computationally expensive task that I performed with this object was to get the full path to the location and display it as text. For example, with the location of the location “Waterloo” I want to show “Waterloo | London | United Kingdom”. This includes moving around the entire set (to the root of the node).

To reduce the cost of this, I created a new field in the Location object that can be printed with this value (and updated as / when the name of the location (or any location in the tree) changes). Given that my application is in a living state, I need to avoid starting this process as one, since this can lead to a rather intense one-time hit on the database, instead I would like to apply this update as and when every place (without this value) . I suggested that the Doctrine postLoad event mechanism would be ideal for achieving this, however.

Location objects are not loaded directly by my application, they will always be the other side of the relationship. With this, there is the mind and the fact that the doctrine postLoad event:

  • Does not load (allows access) to any associated data
  • Installed only for property owners

I have no way to carefully make these changes.

Anyone have any tips or experience on this?

+5
source share
1 answer

I was able to load the associated Location objects into the postLoad event using the initializeObject () method in Entity Manager.

/**
 * Upon loading the object, if the location text isn't set, set it
 * @param \Doctrine\ORM\Event\LifecycleEventArgs $args
 */
public function postLoad(\Doctrine\ORM\Event\LifecycleEventArgs $args)
{
    $this->em = $args->getEntityManager();
    $entity = $args->getEntity();

    if ($entity instanceof \Entities\Location)
    {
        if (is_null($entity->getPathText()))
        {
            $entity->setPathText("new value");
            $this->em->flush($entity);
        }
    } elseif ($entity instanceof {parent Entity})
    {
        $location = $entity->getLocation();
        // This triggers the postLoad event again, but this time with Location as the parent Entity
        $this->em->initializeObject($location);
    }
}
+6
source

All Articles