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.
I don't think there's some important reason, maybe it's just that if you change the superglobal you're referring to afterwards, you haven't got to replace it in the whole code of your class, but just in the constructor.
From this point of view, I find not very sensible the write
method of the first implementation you provided, that writes both class property and session variable, as you remarked.
All of this seems a bit overkill (and overthink), however. Just keep simple and do things that are useful to you.