Getting a “true” object from a proxy object in doc

2020-05-19 20:59发布

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.

10条回答
叛逆
2楼-- · 2020-05-19 21:34

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.

查看更多
甜甜的少女心
3楼-- · 2020-05-19 21:37

This will both convert the reference to a real object and fetch all the fields.

$entityManager->refresh($proxyObject);
查看更多
放我归山
4楼-- · 2020-05-19 21:38

The Symfony PropertyNormalizer gets around this issue using the ReflectionClass 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.

查看更多
Luminary・发光体
5楼-- · 2020-05-19 21:38

If you first used $em->getReference and then $em->find, then the result will be a _proxy. I recommend using:

 createQueryBuilder ... ->getQuery()
    ->setHint (Query::HINT_FORCE_PARTIAL_LOAD, true)
    ->getOneOrNullResult();
查看更多
登录 后发表回答