Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Doctrine 2: Can entities be saved into sessions?

I'm having a problem with lazy loading after I save an entity into a PHP session. Is there any workaround for this?

like image 876
blacktie24 Avatar asked Sep 19 '11 15:09

blacktie24


2 Answers

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);
}
like image 147
karailiev Avatar answered Oct 26 '22 23:10

karailiev


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.

like image 24
Arnaud Le Blanc Avatar answered Oct 27 '22 00:10

Arnaud Le Blanc