Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony EntityRepository return instance of "Proxies\__CG__ MyModelName"

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?

like image 374
Роман Слободзян Avatar asked Jan 18 '16 17:01

Роман Слободзян


2 Answers

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.

like image 86
jbafford Avatar answered Sep 28 '22 08:09

jbafford


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: Entities, Proxies and Reflection.

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.

like image 31
Stanislav Terletskyi Avatar answered Sep 28 '22 07:09

Stanislav Terletskyi