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 complicated, just easy to understand and a useful feature for this class.
Session
justify its existence? How is code that uses it simpler and/or more useful than code that uses$_SESSION
? What have you abstracted away? \$\endgroup\$ArrayAccess
? \$\endgroup\$