I'm having a problem with lazy loading after I save an entity into a PHP session. Is there any workaround for this?
2 Answers
See Serializing Entities in doctrine manual: (Everything you save in a session is serialized and deserialized.)
Serializing entities can be problematic and is not really recommended, at least not as long as an entity instance still holds references to proxy objects or is still managed by an EntityManager.
There is a technical limitation that avoid private properties from being serialized when an entity is proxied (lazy-loaded entities are proxied).
This means that you have to avoid using private
properties for the entities you want to serialize (use protected
entities instead).
Also, if a lazy-loaded entity is not loaded at serialization time, it won't be loadable after de-serialization. So you have to make sure the entity is fully loaded before serializing it.

- 98,321
- 23
- 206
- 194
-
Thx Arnaud, that makes a lot of sense! Is there a specific way to fully load an entity (for just this one instance)? – blacktie24 Sep 19 '11 at 15:27
-
2cloning it seems to be a good way to do it; this also removes references to entity persisters etc, which you must do too. – Arnaud Le Blanc Sep 19 '11 at 15:31
-
Arnaud, how does cloning solve this issue? Wouldn't the cloned object still have a reference to a proxy? – blacktie24 Sep 19 '11 at 18:12
-
2proxies have a `__clone` method that ensures the entity is loaded, and removes references to the entity persister. `__clone` is called by PHP on the clone, just after cloning. – Arnaud Le Blanc Sep 19 '11 at 18:32
-
Arnaud, thx so much for your help! One last question, what happens if you don't remove the entity persister? – blacktie24 Sep 19 '11 at 18:39
-
it will be serialized too, and bad things will happen – Arnaud Le Blanc Sep 19 '11 at 18:40
The accepted answer quotes accurately the Doctrine documentation.
However, there are few more pages on the subject explaining how to serialize entities and store them the session. Entities in the Session says that the entities must be detached before storing in the session and then merged when restoring from the session.
On this page there are sections about detaching and merging entities.
Saving:
$em = GetEntityManager();
$user = $em->find("User", 1);
$em->detach($user);
$_SESSION['user'] = $user;
Restoring:
$em = GetEntityManager();
session_start();
if (isset($_SESSION['user']) && $_SESSION['user'] instanceof User) {
$user = $_SESSION['user'];
$user = $em->merge($user);
}

- 124
- 2
- 9