Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 NativeSessionStorage usage?

EDIT: 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?

EDIT2:

Is a better solution to use a service?

like image 518
Aleš Avatar asked Jun 13 '12 14:06

Aleš


1 Answers

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)

like image 161
Ivan Kvasnica Avatar answered Oct 21 '22 23:10

Ivan Kvasnica