I wanted to create a wrapper for Session
and Request
so that I don't have to access the PHP superglobals directly. I realized that if I create a wrapper for the superglobals and use them, unit testing my application will be easier as the wrapper class can be mocked.
While trying to create my wrapper class, I researched some sample wrapper classes. Some of them stores the superglobal as a class property at initialization:
class Session
{
protected $vars;
public function __construct()
{
session_start();
// POINT OF INTEREST
// Store the superglobal as a class property
$this->vars = $_SESSION;
}
public function get($index)
{
// POINT OF INTEREST
// Accesses the class property instead of the superglobal
return $this->vars[$index];
}
public function write($index, $value)
{
// Writes both class property and session variable
$this->vars[$index] = $value;
$_SESSION[$index] = $value;
}
}
My question: is there any particular reason why while creating a wrapper class we store the superglobal as the class' property instead of accessing them directly? Contrast the above code with this one:
class Session
{
public function __construct()
{
session_start();
}
public function get($index)
{
// Accesses the superglobal directly
return $_SESSION[$index];
}
public function write($index, $value)
{
// Accesses the superglobal directly
$_SESSION[$index] = $value;
}
}
IMO, since the wrapper class would be mocked anyway, why bother storing the superglobals as a class property? Is there a particular reason why so many people do this? Should I store the superglobals as a property in their wrapper instead of accessing it directly?
Thanks for any input.