user1041880 user1041880 - 1 year ago 129
PHP Question

Store objects in sessions Symfony 2

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.

The application will use entities like Product, Category, ShoppingCart where Product and Category are persisted into the database and users will be choosing products into their ShoppingCart.

I have found NativeSessionStorage class which is supposed to save an entity into a session. But there is no written process of implementation into an application.

Do I use this in the controller or in a separated class ShoppingCart? Could you give me a short example of


The question was not set correctly:

The goal is not to save all product ids into a cookie. The goal is to save only a reference for basket (filled with products) in application memory on server-side and assign proper basket to user. Is this even possible to do this in PHP?


Is a better solution to use a service?

Answer Source

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.

Also, take a look to the other ways to store your data : Multiple SessionStorage

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download