Symfony EntityRepository return instance of “Proxi

2020-07-06 02:54发布

问题:

Query

$em->getRepository($this->getRepositoryName('AppBundle:User'))->find($id);

return object instance of Proxies\__CG__\AppBundle\Entity\User instead of AppBundle\Entity\User. What the reason of this?

回答1:

Doctrine is giving you a proxy object from an auto-generated class that extends your entity and implements \Doctrine\ORM\Proxy\Proxy. You can view the code for these auto-generated classes in app/cache/dev/doctrine/orm/Proxies/.

The proxy object allows for a set of behaviors that Doctrine provides that you would otherwise have to explicitly code into your entity, including support for lazy-loading of properties. For example, if your object has a reference to another entity (such as from a OneToOne/OneToMany/ManyToOne/ManyToMany association), you don't necessarily want to always load those references when you retrieve your User record, because they may not be relevant all the time. Lazy-loading allows that data to be brought in later on-demand.

In order to perform that lazy loading, the entity needs to have access to Doctrine so it can ask Doctrine to retrieve the relevant data. This is done through an __initializer__ property that is provided to the proxy object. The rest then happens, handled by Doctrine, without your code needing to know the details.



回答2:

Sometimes we need to respectively determine real class name for an Entity.

Doctrine uses static methods, placed in a helper class: 'Doctrine\Common\Util\ClassUtils', for generating name of proxy class. Here is description: Class ClassUtils.

In case you want to get a real class name, just use:

$entityClassName = ClassUtils::getClass($entityObject);.

I've found this useful for logging of entity data changes (original entity can be determined by id and class name).

Hope it was helpfull.