chitika Ad

Saturday, 1 March 2014

Zend Framework 101: Zend_Session

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.

No comments:

Post a Comment