I am writing a small e-shop application with Symfony 2 and I need some way to store the user\'s shopping cart in a session. I think using a database is not a good idea.
Don't know if this way is the better way to store your data temporary. You can use this to instantiate a session object :
$session = $this->get("session");
Don't forget the 'use' in your controller :
use Symfony\Component\HttpFoundation\Session;
Then, the session starts automatically when you want to set a variable like :
$session->set("product name","computer");
This is based on the use of the Session class, easy to understand. Commonly definitions :
get(string $name, mixed $default = null)
Returns an attribute.
set(string $name, mixed $value)
Sets an attribute.
has(string $name)
Checks if an attribute is defined.
Also, take a look to the other ways to store your data : Multiple SessionStorage
You can save the whole object into a session with Symfony. Just use (in a controller):
$this->get('session')->set('session_name', $object);
Beware: the object needs to be serializable. Otherwise, PHP crashes when loading the session on the start_session() function.
Just implement the \Serializable interface by adding serialize() and unserialize() method, like this:
public function serialize()
{
return serialize(
[
$this->property1,
$this->property2,
]
);
}
public function unserialize($serialized)
{
$data = unserialize($serialized);
list(
$this->property1,
$this->property2,
) = $data;
}
Source: http://blog.ikvasnica.com/entry/storing-objects-into-a-session-in-symfony (my blogpost on this topic)
You can make your entity Serializable and serialize the entity object and save to session and then retrieve in other page using unserialize()
. There is one caveat, for an entity that exists in the db Doctrine2 will mark the retrieved/unserialized entity as detached. You have to call $em->merge($entity);
in this case.