Doctrine uses proxy objects to represent related objects in order to facilitate lazy loading. This is a really cool feature, but its causing an issue with something I am trying to accomplish.
I have customized my user object so that they are all required to be related to a different object, which I will call city. This relationship is working fine.
I have a form that my user fills out to generate another object, street. Street is also related to the city object. Instead of having my user select the city when they fill out the form, I want to automatically set it before I persist the object to my database.
I tried using $event->setCity($user->getCity())
, but since $user->getCity() returns a proxy object, this generates an error. Is there a function I can call from the proxy object to get the real one?
Note: I am aware I can create a custom query with a join to force doctrine to actually load the related object, but since this is the user (using FOSUserBundle) that would be difficult to do properly.
The solution I found is to extend the
Reflection Hydrator
and use the new class as Hal extractor params, for complex entities.You can find the code here:
Synergy of proxy object of doctrine and zend expressive hal
probably.
This will both convert the reference to a real object and fetch all the fields.
The Symfony
PropertyNormalizer
gets around this issue using theReflectionClass
getParent
method. If you need to inspect the object, as for a normalizer, rather than just use the->get
methods, you should be able to use a similar approach.It appears the Proxy has a parent of the actual entity, which is why instanceof still works.
If you first used
$em->getReference
and then$em->find
, then the result will be a _proxy. I recommend using: