Store objects in sessions Symfony 2

后端 未结 3 1326
终归单人心
终归单人心 2021-02-07 23:58

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.

3条回答
  •  北海茫月
    2021-02-08 00:35

    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)

提交回复
热议问题