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:
- You have installed Zend Framework and set up the necessary include paths
- You have read the documentation pertaining to Zend_Session
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.
Over 200 resources for freelance web designers and developers
While browsing around the local blogosphere I found this really helpful post. Thanks Chris.
You can read his post or go directly to the list of resources here. This list is pretty exhaustive and I can’t imagine how long it must have taken to put it together. Bloggers have to be some of the most helpful people in the world, period.
Beginners tips for form processing with PHP
I remember when first starting with the whole PHP / Web development scene that processing forms was a real hassle. This was back in the day when php_global_vars was still accepted as the “in” thing and you had to use each form variable as php variable. I only found out about $_GET (or as it was $HTTP_GET_VARS) later on, much to my consternation.
I did however, come up with a workaround at the time, and it’s stuck with me ever since. I fully realise that the PHP superglobals make this method somewhat redundant, but I still find it useful in larger forms, especially when you’re trying to group related form variables.
The basic idea is to add each form variable to an array. In my case this array is usually called “items”. For instance, I have a standard login form with the usual login and password fields. I define each field using the following method : <input type=”text” name=”items[login]” value=”” /> – for the novices out there, notice the “items[login]” bit. What this does is assign the value for “login” to the “items” array. This array is then accessed via the $_GET[“items”] or $_POST[“items”] superglobals. Of course you can have multi-dimensional arrays – for example : <input type=”text” name=”items[user][login]” /> and so on and so forth.
Now the really useful part comes in when you are looking to sanitize only certain parts of your user input (yes I’ve had instances where I purposely didn’t want to sanitize incoming data). For a good tutorial on how to sanitize user input – try this one . You can also assign input data to a session variable more easily. I.e $_SESSION[“userdata”] = $_GET[“items”][“user”].
Lately, I’ve found this method extremely useful when binding form data to my MVC model data. So lets say we have a form where a user can edit his/her profile. In addition, this form also has space for the user to edit his password. Usually, password and profile information is stored in 2 separate tables. Which means that I would use “user[]” for the password fields (since you need a “confirm password” field aswell) and I would use “profile[]” for the user’s profile data. Then once inside the PHP script, I can then bind $_GET[“user”] to my user model, and $_GET[“profile”] to my userProfile model. The only constraint then is making sure the form field matches a model field.
I admittedly haven’t seen this method being used all that often, and it does make me wonder if it goes against some “best practice” that I’m ignorant of, or perhaps I’m just way ahead of my time 😉
Either way, hopefully it can be of some help to someone out there. I do promise though, that when I’ve improved my blogging and therefore writing skills, I’ll revisit this post and make it more “noob” friendly.