Home > PHP > Simple PHP wrapper class for Zend Session

Simple PHP wrapper class for Zend Session


I’ve been rather busy lately writing a new personal CMS based loosely on the excellent Zend Framework.

One of the decisions I had to make was on how to handle session data, usually an overlooked yet very important aspect to any interactive website today. Fortunately, Zend Framework makes this a very easy decision to make with the introduction of their Zend_Session management component.

The problem with frameworks though, is that you risk tying your code up too tightly with that of the framework itself. What happens when that bigger, better and shinier framework comes out ? Do you rewrite everything – again, or do you just resign yourself to using the old system until it’s well past it’s sell by date ?

While you cannot avoid the entanglement all together (you do need to make use of the framework after all), you can add abstraction layers – within reason.

It’s with this in mind that I created the following abstraction class. If I ever decided to use some other package/component to manage my sessions, I’d only have to edit code in one place – the class itself.

Keep in mind that this is an extremely basic example and should be treated as such.
I’m also going to assume the following:

First our session wrapper/abstraction class :

<?php
require_once("Zend/Session.php");

class SessionWrapper {
    protected static $_instance;
    public $namespace = null;
	
	private function __construct() {
			/* Explicitly start the session */
			Zend_Session::start();
			
			/* Create our Session namespace - using 'Default' namespace */
			$this->namespace = new Zend_Session_Namespace();

			/** Check that our namespace has been initialized - if not, regenerate the session id 
			 * Makes Session fixation more difficult to achieve
 			 */	
			if (!isset($this->namespace->initialized)) {
			    Zend_Session::regenerateId();
			    $this->namespace->initialized = true;
			}
	}
	
	/**
	 * Implementation of the singleton design pattern
	 * See http://www.talkphp.com/advanced-php-programming/1304-how-use-singleton-design-pattern.html 
	 */	
	public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }
    
    /**
     * Public method to retrieve a value stored in the session
     * return $default if $var not found in session namespace
     * @param $var string
     * @param $default string
     * @return string
     */
    public function getSessVar($var, $default=null){
    	return (isset($this->namespace->$var)) ? $this->namespace->$var : $default;
    }
    
    /**
     * Public function to save a value to the session
     * @param $var string
     * @param $value
     */ 
    public function setSessVar($var, $value){
    	if (!empty($var) && !empty($value)){
    		$this->namespace->$var = $value;
    	}
    }
}
?>

Note that the class takes advantage of the Singleton Design Pattern. What this means is that you only need to create an instance of the class once. You can then access that instance from anywhere within your project without having to either create yet another instance or include “global” objects/variables. You can do some further reading here for a good tutorial and explanation on implementing the Singleton Design Pattern in PHP.

Also note that the class starts the session explicitly. This means that you’ll need to include and instantiate this class before ANY headers are sent to the browser (though this should be obvious to the more seasoned coder). If you get any “Cannot modify header information – headers already sent” errors, please go back and read the manual, make sure you understand how PHP Sessions work and then come back to this post.

Now for some example usage :

<?php
// make sure SessionWrapper::getInstance() is called at least once in your bootstrap script
// to make sure that the session is created before any headers are sent to browser
$mySession = SessionWrapper::getInstance();

// Set a session value
$mySession->setSessVar("example", "my value");
// this is the same as saying 
$_SESSION["Default"]["example"] = "my value";

// Print a session var to screen
echo $mySession->getSessVar("example", "default value");
// outputs "my value" - same as saying the following
echo $_SESSION["Default"]["example"];

// You can also use the following notation :
SessionWrapper::getInstance()->getSessVar("example");

// You can use the above code inside a function without having to 'global' $mySession
function myExample(){
	return SessionWrapper::getInstance()->getSessVar("example");
}

?>

So, this may all seem pretty pointless at the moment, since you can access the Session directly through either $_SESSION or create a new instance of Zend_Session_Namespace(). But – if for some reason you find a better session management package and want to move away from Zend_Session – all you have to do is modify the SessionWrapper constructor method and it’s finished. No exhaustive search and replace necessary.

Advertisements
  1. September 23, 2008 at 6:07 pm

    Great stuff!

    Minor nitpick though. I noticed you are starting your comment blocks with “/*”. I was under the impression the convention was to start it with “/**”. Could be wrong though, I carry this on from my (at the time) extensive Java experience from about 5 years back.

    Otherwise, very neat formatting, wd! I love clean code, not like my own is always that great. 🙂

  2. calisza
    September 24, 2008 at 1:22 pm

    You’re right on both counts, it should be /** and that was a nitpick 🙂 Fixed.

  3. jan
    February 1, 2010 at 12:51 pm

    GREAT! just what I was looking for.

  4. yknip
    March 27, 2010 at 8:49 pm

    Your setSessVar function does not permit a session variable to be set to 0 (or to any other value for which empty returns true). Fix things up like this:
    public function setSessVar($var, $value){
    // if (!empty($var) && !empty($value)){
    if ( !empty($var) ){
    $this->namespace->$var = $value;
    }
    }

  5. Vincent
    September 3, 2010 at 8:40 pm

    Can you please extend this wrapper to store and use sessions in MySQL Database?

  1. March 1, 2011 at 4:51 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: