Question

I'm using Symfony2 and Doctrine 2.0. I'm trying to read data from an XML feed and map this to new or existing entities in the database. When data in the XML feed changes I need update existing entities, but when the data is added I should create new entities.

In my entity classes I'm using the following denormalize methods to map the XML data to the entity's properties:

function denormalize(SerializerInterface $serializer, $data, $format = null) 

(Defined in Symfony\Component\Serializer\Serializer called inside my Entity classes)

The docs for this method state that "It is important to understand that the denormalize() call should denormalize recursively all child objects of the implementor." and this is what I'm trying to do. However entities should not know about the EntityManager so how do I check, inside the denormalize() method if a related/child entity already exists or not?

Kind regards, Matthew

Was it helpful?

Solution 2

I think my problem was in my approach and not really my code!!

Originally, each time I found an entity represented in the XML I would check (using the EntityManager) to see if it was new or existing BEFORE denormalizing it. I took this route because there is duplication in the XML and I was worried about creating duplicate entities in the EntityManager. Cheacking to see if an entity already existed meant I could update the existing entity rather than create a duplicate. Now with my new approach every time I find an entity represented in the XML I denormailze it into a new entity. Of course this creates duplication in the EntityManager, just as there is in the XML, but this can be handled later, hopefully..!

So far this is proving to be a better solution, although I am experiencing some issues when trying to merge the duplicate entities in the EntityManager using $em->merge(); and cascade={"persist", "merge"}. I've posted a new question about this here: Doctrine 2.1 - Relation Lost After ManyToMany Cascade Merge - Symfony2

Matthew

OTHER TIPS

It is indeed a bad idea to call the EntityManager in an entity (and, as far as I know, outside a controller).

I've never faced that problem, but if I were you I'd try to denormalize in one of your controllers, or if it really bothers you, in a service that you call in a controller, and to which you give your EntityManager (here again, best do it in the controller itself, or simply send your objects to the service so it can denormalize the xml "into" the objects).

Best would be to write a controller that works no matter the entity given.

Hope that helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top