Proxies
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. When your application then requests a property or calls a method of this proxied entity, Doctrine will load the entity from the database (except when you request the ID, which is always known to the proxy).
This happens fully transparent to your application due to the fact that the proxy extends your entity class.
Doctrine will by default hydrate associations as lazy load proxies if you don't JOIN
them in your query or set the fetch mode to EAGER
.
Now I must add this because I don't have enough reputation to comment everywhere:
Unfortunately, Crozin's answer contains misinformation.
If you execute a DQL query like
SELECT u.id, u.username FROM Entity\User u WHERE u.id = :id
you won't get a (proxied) entity object, but an associative array. So it's not possible to lazy load any additional properties.
With this in mind, one comes to the conclusion that the use case example won't work either.
The DQL would have to be changed to something like this in order to access $article
as object:
SELECT a FROM Entity\Article a ORDER BY a.createdAt DESC LIMIT 25
And the property returned by getContent()
would have to be an association in order not to load the content properties of all 25 entities.
Partial Objects
If you want to partially load entity properties that are not associations, you have to tell this Doctrine explicitly:
SELECT partial u.{id, username} FROM Entity\User u WHERE u.id = :id
This gives you a partially loaded entity object.
But beware that partial objects are not proxies! Lazy Loading doesn't apply to them. Therefore, using partial objects is generally dangerous and should be avoided. Read more: Partial Objects — Doctrine 2 ORM 2 documentation