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.
The Proxy object allows you to create an object that can be used in place of the original object, but which may redefine fundamental Object operations like getting, setting, and defining properties. Proxy objects are commonly used to log property accesses, validate, format, or sanitize inputs, and so on.
A Doctrine proxy is just a wrapper that extends an entity class to provide Lazy Loading for it. By default, when you ask the Entity Manager for an entity that is associated with another entity, the associated entity won't be loaded from the database, but wrapped into a proxy object.
A proxy object acts as an intermediary between the client and an accessible object. The purpose of the proxy object is to monitor the life span of the accessible object and to forward calls to the accessible object only if it is not destroyed.
It means the place where our data can be accessed from, a repository of data. This is to distinguish it from a database as a repository does not care how its data is stored.
This is unlikely to help in the specific instance for the question, since you're relying on a third-party module, but you can prevent the lazy loading by setting the "fetch mode" for your entity to "EAGER".
User: ManyToOne: city: fetch: EAGER
This can also be handled by annotations:
@ManyToOne(targetEntity="city", fetch="EAGER") @JoinColumn(name="city", referencedColumnName="id")
See http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#annref-manytoone
None of the other answers I've seen here worked for me.
Edit: As mention by @flu this approach don't return the "true" object. However it can be useful in case if you need the data from the object. Then, you can just get the real object from ObjectManager by some of identity.
We can use __load() method from Proxy interface
$proxyObject->__load();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With