Instead of using $_COOKIE and $_SESSION directly, you create objects with methods like Session::get('some_var');
. Then when it runs on the website you access $_SESSION, but when run for tests you use a simple array. Ideally you would make different adapters for the different environments.
As a very basic example:
class Session
{
private $adapter;
public static function init(SessionAdapter $adapter)
{
self::$adapter = $adapter;
}
public static function get($var)
{
return self::$adapter->get($var);
}
public static function set($var, $value)
{
return self::$adapter->set($var, $value);
}
}
interface SessionAdapter
{
public function get($var);
public function set($var, $value);
}
public class PhpSessionAdapter implements SessionAdapter
{
public function get($var)
{
return isset($_SESSION[$var]) ? $_SESSION[$var] : null;
}
public function set($var, $value)
{
$_SESSION[$var] = $value;
}
}
public class MemorySessionAdapter implements SessionAdapter
{
private $session = array();
public function get($var)
{
return isset($this->session[$var]) ? $this->session[$var] : null;
}
public function set($var, $value)
{
$this->session[$var] = $value;
}
}
Then in your code for the website you start with Session::init(new PhpSessionAdapter());
, and for testing you use Session::init(new MemorySessionAdapter());
. Then in the rest of the code just use Session::get
and Session::set
without worrying the data actually goes / comes from.