Thomas K
Thomas K

Reputation: 6196

Reflection on a doctrine2 proxy object

As far as I can see, reflection methods like property_exists() won't work on doctrine2 proxy objects.

In this case, the proxy is retrieved thru a relationship $user->getCity()

How can I check if a property exists / is set in this case?

Upvotes: 3

Views: 3159

Answers (2)

Aerendir
Aerendir

Reputation: 6379

The solution is ReflectionClass::getParentClass().

So a code like this should work:

$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);

Upvotes: 10

Ocramius
Ocramius

Reputation: 25431

You may want to check if the proxy is initialized first:

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

This basically enforces loading of the proxy: after that, everything will just work as if you had an instance of the original entity.

Public properties are not currently supported by the ORM by the way, though the feature will be implemented in Doctrine ORM 2.4. That way, you will just be able to access public properties without worrying about the object being or not a proxy.

Upvotes: 3

Related Questions