PhpRiot
Follow phpriot on Twitter
Sponsored Link
Download Article
Download this article or the entire “Zend Framework 101” series with all listings and files.




More information
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store
Free iPad/iPhone App
Available on the App Store

  • PHP manual
  • Zend Framework manual
  • Smarty manual
  • PHP articles
  • PHP training

Related Books
PHP Solutions: Dynamic Web Design Made Easy

PHP Solutions: Dynamic Web Design Made Easy

This is the second edition of David Power's highly-respected PHP Solutions: Dynamic Web Design...

PHP for the World Wide Web, Third Edition

PHP for the World Wide Web, Third Edition

With PHP for the World Wide Web, Third Edition: Visual QuickStart Guide , readers can start from...

Zend Framework 101: Zend_Session

Creating Session Namespaces

The Zend Framework provides advanced session handling using the Zend_Session component. Using this component, you no longer need to access PHP's $_SESSION global variable.

Note: In fact, you should not access $_SESSION at all when using Zend_Session.

Zend_Session uses namespaces to store your session data. That is, when you want to read or write session data you must first specify a namespace. This allows you to easily store different session data without worrying too much about other values stored in the session.

You create a new session namespace by instantiating the Zend_Session_Namespace class. The first argument to the constructor is the name of the namespace. Listing 1 shows an example of this.

Listing 1 Creating a namespace for storing user identity data (listing-1.php)
<?php
    require_once('Zend/Session.php');
 
    $session = new Zend_Session_Namespace('identity');
?>

We can now read or write session data in the identity namespace using the $session variable. I will show you how to do this shortly.

Note also that you do not need to manually start sessions (using the session_start() function) as you might have in the past when using sessions in PHP. Instantiating this class takes care of this for you.

Note: As always, session handling must be performed prior to performing any output. This is easy to achieve if you're using Model-View-Controller (or similar – that is, performing any required processing in your scripts prior to output), or if you use output buffering. If you want to force sessions to start earlier in your script without creating a specific namespace, you can call Zend_Session::start() instead.

Internally, the above code will be accessing data in the $_SESSION['identity'] variable. You should never access this directly.

In This Article