How to clear a session container in Zend framework2

aravind.udayashankara picture aravind.udayashankara · Mar 4, 2013 · Viewed 22.5k times · Source

I have recently started building an application using Zendframework 2 , I have good experience in ZF1 , the major problem I am facing here with ZF2 is with sessions .

Here is the way that I am creating a session container .

use Zend\Session\Container;

// Session container creation: ( previously we were calling it as namespaces )

$session_user = new Container('user');
$session_user_errors = new Container('usererrors');
$session_user_shares = new Container('usershares');

Now Like this I have several containers ,

I could clear a key of a particular container like this

// Getting value from the session by key: ( get value from namespace )

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

// Setting value in session: ( set value from namespace )

$session_user->offsetSet('username', 'abcd');

Now my problem is to clear an entire container which are set in several levels of my application .

If I try the below code Its clearing all of my session containers .

$session_user = new Container('user');
$session_user->getManager()->getStorage()->clear();

I want to clear only the container called 'user' which has many keys ( I dont know what all will be there at end ) . Is there a way to achieve this

I know I can do offsetunset on each key but thats not an Optimal solution I feel .

Please kindly suggest if any alternative way is there to clear a particular session container .

NOTE : - I am not using any of the third party modules like ZfcUser and Akrabat sessions

Thanks in advance for responding to this posting .

Answer

Crisp picture Crisp · Mar 4, 2013

You almost had it, you just need to pass the namespace to the clear method

$session_user->getManager()->getStorage()->clear('user');

You can still treat the $_SESSION like an array, too, so the following also works

unset($_SESSION['user']);