Doctrine2: dependency graph for a set of objects

Using Symfony and Doctrine, I am writing a component that populates the database with elements of arbitrary objects during application deployment.

I want this component to be shared, so I'm trying to automatically resolve dependencies between objects and insert them in the correct order.

Currently, I get the dependencies of each individual object through the metadata of the object, recursively:

public function getEntityDeps($eName) { $deps = []; foreach ($this->entityManager->getClassMetadata($eName)->getAssociationMappings() as $mapping) { $deps[] = $mapping['targetEntity']; $deps = array_merge($deps, $this->getEntityDeps($mapping['targetEntity'])); } return $deps; } 

The result is obviously a list of the following form:

 // NOTE: The real list of course contains class names instead of entity aliases. [ "FooBundle:EntityA" => [], "FooBundle:EntityB" => ["FooBundle:EntityA", "FooBundle:EntityC"], "FooBundle:EntityC" => ["FooBundle:EntityA"], "BarBundle:EntityA" => ["BarBundle:EntityB"], "BarBundle:EntityB" => [] ] 

The next step, I think, will apply some type of topological sorting to the list.

However, I am not sure if I can use the general algorithm here or if I forgot something. Moreover, the entities are not necessarily connected (so in fact we can have more than one dependency graph).

Also, I hope they have Doctrine internal functionality that can sort for me.

So, what would be the most reliable way to sort an arbitrary set of Doctrine objects? Is it possible to reuse Doctrine?

+5
source share
1 answer

So, after digging through the Doctrine source code for a while, I found that they really have an implementation of topological sorting (DFS, for that matter). It is implemented in Doctrine\ORM\Internal\CommitOrderCalculator .

Where is this CommitOrderCalculator used? In UnitOfWork , of course.

So, instead of manually calculating the correct commit order, I just needed to ... move the call to $em->flush() outside the foreach that went through the entities and let UOW do the work itself.

Duh.

0
source

Source: https://habr.com/ru/post/1235126/


All Articles