Search code examples
phpsessionzend-framework2

How to use Zend\Session in zf2?


Does anybody try zf2? I can not understand new mechanism of using sessions in zf2. How can I write and read to/from the session in new zend framework?

Also I can not find any examples in the internet.


Solution

  • Some examples of zf2 sessions usage:

    Session creation:

    use Zend\Session\Container;
    $session = new Container('base');
    

    Check that key exists in session:

    $session->offsetExists('email')
    

    Getting value from the session by key:

    $email = $session->offsetGet('email');
    

    Setting value in session:

    $session->offsetSet('email', $email);
    

    Unsetting value in session:

    $session->offsetUnset('email');
    

    And other easy way to use session are:

    $session = new Container('foo');
    

    // these are all equivalent means to the same end

    $session['bar'] = 'foobar';
    
    $session->bar = 'foobar';
    
    $session->offsetSet('bar', 'foobar');