Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 208
rdo Avatar asked Jan 24 '12 16:01

rdo


4 Answers

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'); 
like image 134
rdo Avatar answered Nov 12 '22 14:11

rdo


Definitely yes, you should use Zend\Session\Container

Container extends of ArrayObject and instantiates with ARRAY_AS_PROPS flag that means you can easily iterate through properties and read/write them, e.g.

use Zend\Session\Container as SessionContainer;

$this->session = new SessionContainer('post_supply');
$this->session->ex = true;
var_dump($this->session->ex);

First argument is session namespace and second — Manager. Manager is a facade for Storage and SaveHandler and it's configured with ConfigInterface in order to save your session data in DB or Memcache server.

like image 40
dVaffection Avatar answered Nov 12 '22 13:11

dVaffection


I'm currently working with zf2. I found usage of Sessions in:

Zend\Authentication\Storage\Session.php

Maybe you can find your answer there.

like image 3
ohartl Avatar answered Nov 12 '22 13:11

ohartl


If you are trying to use session in your login action, you can use: "Zend\Authentication\AuthenticationService". It Authenticates the user and store session as well.

getStorage()->write($contents) will store the session.

like image 1
musafar006 Avatar answered Nov 12 '22 14:11

musafar006