Tuesday, December 4, 2012

Using Sessions

Using sessions in Zend Framework 2 is very easy - probably easier than you would expect. With the lack of official documentation, this short article serves as a quick start.

It will probably not be a surprise to you that sessions in Zend Framework 2 are handled within the Zend\Session namespace. To interact with sessions, we will actually use the Zend\Session\Container class.

Because ZF2 makes use of namespaces, we must add the following at the top of our controller, given that we do not want to use fully qualified classes:

use Zend\Session\Container;

Then, in a controller action, we can save a session like this:

$user_session = new Container('user');
$user_session->isLoggedIn = true;

To retrieve the above value, simply do like this:

$user_session = new Container('user');
$is_logged_in = $user_session->isLoggedIn;

The reason why we can use properties like above is that the Container class extends the ArrayObject class and uses the ArrayObject::ARRAY_AS_PROPS constant. Actually, the $_SESSION superglobal is replaced by a Zend\Session\Storage\SessionStorage object.

This is essentially how you can easily work with sessions in Zend Framework 2. Obviously there are many more aspects to it for more advanced use cases, but that is outside the scope of this quick start guide.

For more detailed information regarding what happens behind the scenes when working with Zend Framework 2 sessions, I encourage you to visit the previous link or wait for the official documentation to be ready.