phpsessionobjectzend-framework2zend-session

how to store an object inside session in zend framewrok 2?


i am wondering if i can store a object inside session using zend frameworks 2

when i retrieve the object it needs to be an object and not an array

example object:

object(Zend\Stdlib\Parameters)[144]
  public 'name' => string 'test test' (length=9)
  public 'website' => string 'test.com' (length=8)
  ...

any ideas?


Solution

  • In Zend Framework 2, The session seems to be an associative array with key as namespace, and value as another associative array.

    In order to manipulate the session, you can use an abstraction layer called Container

    use Zend\Session\Container;
    
    // namespace 'user'
    $userContainer = new Container('user');
    
    // Store the locale and devise
    $userContainer->locale = 'fr-FR';
    $userContainer->devise = 'Euro';
    

    to write what you want under a specific namespace. You can later retrieve you data with:

    use Zend\Session\Container;
    
    // Create a container to manipulate session data
    $userContainer = new Container('user');
    
    // Check if the data exist under the namespace
    if ( $userContainer->offsetExists('devise'))
    {
        // Retrieve the data
        $devise = $userContainer->offsetGet('devise');
    }
    else
    {
        // Get the default value
        $devise = 'Euro';
    }
    

    PS: Of course, be sure that the session is available