HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

A wrapper class for Sessions in PHP

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
phpwrapperforclasssessions

Problem

I have been using $_SESSION, $_POST, $_GET, $_SERVER globals directly without ever knowing there was a concept/practice called, "Wrapping globals in classes" until, yesterday. As I did, I was able to immediately understand its effective benefit / usefulness. But I searched for a good wrapper, for $_SESSION, $_GET and $_POST but could not find anything simple/good. So, as a test I made this for the session global.

<?php 

/**
 * A SESSION Wrapper class. 
 * 
 * @category Session
 * @version  1.0.0
 * @Nile
 */

namespace Nile\Lib; 

class Session
{
    protected static $sessionLife = 1200; 

    public static function start()
    {
        if(!headers_sent() && !session_id()){
            if(session_start()){
                session_regenerate_id();
                return true; 
            }
        }
        return false; 
    }

    public static function set($Key, $value)
    {
        $_SESSION[$Key] = $value; 
    }

    public static function has($Key)
    {
        return (bool)(isset($_SESSION[$Key])) ? $_SESSION[$Key] : false; 
    }

    public static function get($Key)
    {
        return (isset($_SESSION[$Key])) ? $_SESSION[$Key] : false; 
    }

    public static function del($Key)
    {
        if(isset($_SESSION[$Key])){
            unset($_SESSION[$Key]);
            return false; 
        }

    }

    public static function destroy()
    {
        if(isset($_SESSION)){
            session_destroy();
        }   
    }

    public static function dump()
    {
        if(isset($_SESSION))
        {
            print_r($_SESSION);     
            return ;
        }

        throw new \Exception("Session is not initialized");
    }

}


And this is the simple session initialization.

Session::start(); // does session_start(); 
Session::set('user', 'isLogedIn'); //does $_SESSION['user'] = 'isLoggedIn';


Considering this is my first wrapper, I would like a review and what I could add next. Something that is not very compl

Solution

I have been using php for over 10 years and never found a need for a session wrapper, but maybe you find it easier/better.

There are a few improvements that could be made with your code

If we are checking to see if the session has a key, a simpler test is

public static function has($Key)
{
    // return (bool)(isset($_SESSION[$Key])) ? $_SESSION[$Key] : false; 
    return array_key_exists($Key, $_SESSION); 
}


The get function here would probably be more useful with a default value option then just returning false.

public static function get($Key, $default=false)
{
    return (self::has($Key)) ? $_SESSION[$Key] : $default; 
}


The del function, I am unsure what you are trying to achieve by returning false, but returning nothing if it isn't set?
Personally I wouldn't bother to check if it is set or not, just unset it, and return nothing. I would also call it delete, so it is painfully obvious to the use what it does

public static function delete($Key)
    {
       if(isset($_SESSION){
            unset($_SESSION[$Key]);
       //         return false; 
       }
    }


The dump function, why do you throw an exception if the session doesn't exist, but not anywhere else if the session doesn't exist? I would re-write it like a guard clause rather then having a return halfway through the function.

public static function dump()
{
    if(!isset($_SESSION))
    {
        throw new \Exception("Session is not initialized");
    }

    print_r($_SESSION);
}


Another useful function you might add is get_once. I do something similar for when I store an error message in the session, then redirect to a new page and display the error message. After that the error message is no longer relevant so I remove it from the session.

public static function get_once($Key, $default=false)
{
    $value = self::get($Key, $default);
    self::delete($Key);
    return $value;
}


Other things you could do is to manage different "namespaces" (maybe not the best word to describe it) within a session.

// keep in mind if you do this, you can't use static everywhere like you have

function __construct($namespace) {
    $this->namespace = $namespace;
}

function set($key, $value) {
   $_SESSION[$this->namespace][$this->key] = $value;
}

// Then you can use simple keys that don't overwrite each other
$user_session = new session('user');
$user_session->set('name', 'Donald Duck');

$page_session = new session('page');
$page_session->set('name', 'Home Page');

Code Snippets

public static function has($Key)
{
    // return (bool)(isset($_SESSION[$Key])) ? $_SESSION[$Key] : false; 
    return array_key_exists($Key, $_SESSION); 
}
public static function get($Key, $default=false)
{
    return (self::has($Key)) ? $_SESSION[$Key] : $default; 
}
public static function delete($Key)
    {
       if(isset($_SESSION){
            unset($_SESSION[$Key]);
       //         return false; 
       }
    }
public static function dump()
{
    if(!isset($_SESSION))
    {
        throw new \Exception("Session is not initialized");
    }

    print_r($_SESSION);
}
public static function get_once($Key, $default=false)
{
    $value = self::get($Key, $default);
    self::delete($Key);
    return $value;
}

Context

StackExchange Code Review Q#62133, answer score: 4

Revisions (0)

No revisions yet.