2013-02-11 88 views
2

據我所知,像property_exists()這樣的反射方法不適用於doctrine2代理對象。關於doctrine2代理對象的思考

在這種情況下,代理通的關係$user->getCity()

如何檢查是否存在財產在這種情況下設置/檢索?

+0

一個doctrine2代理類,就像任何其他類。如果方法在那裏,它應該可以工作。據我所知,教義生成這些包裝方法。確切的用法是什麼?你可以發佈一些代碼嗎? – 2013-02-11 15:19:25

回答

2

您可能要檢查如果代理第一次初始化:

if (
    $entity instanceof \Doctrine\Common\Persistence\Proxy 
    && ! $entity->__isInitialized() 
) { 
    $proxy->__load(); 
} 

這基本上強制代理的負載:在那之後,一切都將只是工作,如果你有原來的實體的實例。

ORM當前不支持公共屬性,雖然該功能將在Doctrine ORM 2.4中實現。這樣,您就可以訪問公共屬性,而不必擔心對象是否是代理。

+0

是的,代理被初始化..所以你說的是我不能使用像'property_exists()'atm這樣的反射方法? – 2013-02-15 07:56:28

+0

你可以,但只有當代理初始化時:否則它所表示的「假」數據結構將是空的。 – Ocramius 2013-02-15 08:36:38

+0

這很奇怪,因爲我確定代理已初始化。順便說一句'property_exists()'計算爲'false'。但是,如果我做$用戶 - >城市,我得到'不能訪問私人財產..'錯誤。奇怪的! – 2013-02-15 14:06:07

0

解決方案是ReflectionClass::getParentClass()

所以像這樣的代碼應工作:

$reflect = new \ReflectionClass($proxyObject); 

if ($proxyObject instanceof \Doctrine\Common\Persistence\Proxy) 
    // This gets the real object, the one that the Proxy extends 
    $reflect = $reflect->getParentClass(); 

$privateProperty = $reflect->getProperty('privateProperty'); 
$privateProperty->setAccessible(true); 
$privateProperty->setValue($proxyObject, $yourNewValue);