Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear a session container in Zend framework2

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 .

like image 846
Aravind.HU Avatar asked Mar 04 '13 05:03

Aravind.HU


2 Answers

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']); 
like image 173
Crisp Avatar answered Oct 10 '22 21:10

Crisp


Following are the details for Destroying the session in Zend Framework 2:

  • Using Basic PHP Functionality

    session_start() function starts the session.

    session_destroy() function deletes ALL the data stored in session array.

Now using Zend Framework functionality:

For clear understanding lets first, create a session in Zend Framework and then make a Delete process.

  1. Creating Session

use Zend\Session\Container;

$session_container = new Container('user_session');

$session_container->last_login = date('Y-m-d H:i:s');

$session_container->sess_token = trim(base64_encode(md5(microtime())), "=");

  1. Deleting Session

$session = new Container("user_session");

$session->getManager()->getStorage()->clear('user_session');

Where user_session is the name of session array key for storing the details.

like image 39
Mohd Belal Avatar answered Oct 10 '22 21:10

Mohd Belal