Symfony2 serialize entity object to session Symfony2 serialize entity object to session symfony symfony

Symfony2 serialize entity object to session


You can serialize any entity by setting all their properties and relationships from private to protected.

You could have a common issue with symfony2, even if you have set all properties to protected: You have to re-generate the proxies of those entities you have changed. To do so, simply clear the cache. For dev enviroment:

app/console cache:clear

It works even if "it contains many foreign objects and even ArrayCollections of foreign entities" as you said.


Serializing entities is not recommended, as you can see in the Doctrine-documentation. You should implement the Serializable-interface and serialize/deserialize the entity-data manually.


You can exclude unnesseary fields by overridding __sleep method:

public function __sleep() {    // these are field names to be serialized, others will be excluded    // but note that you have to fill other field values by your own    return array('id', 'username', 'password', 'salt');}