Session extends DBO
// The application will only include this file once,
// and will only start the session once
session_start();
/**
* The Session class manages data in the user_sessions table,
* while primarily managing the PHP session itself. This structure
* could just as easily store all session information in a database
* table instead of using PHP's built-in session functionality
* and the object interface would not require any change at all.
*/
class Session extends DBO {
public $pk = 'session';
// A reference to the $_SESSION superglobal
protected $session;
// The joining table between users and $_SESSION
protected $table = 'user_sessions';
protected $fields = array(
'user' => null,
'session' => null
);
/**
* Regenerating session IDs can only help security, especially
* when called on successful login via credentials.
*/
public function regenerate() {
session_regenerate_id(true);
$this->fields[$this->pk] = session_id();
return $this->save();
}
/**
* Session::get() overrides DBO::get() in order
* to support transparently retrieving information
* from the session itself.
*/
public function get($key) {
if ($key == 'id') {
return session_id();
} else if ($key == 'user') {
return $this->fields['user'];
} else if (isset($this->session[$key])) {
return $this->session[$key];
} else {
return false;
}
}
/**
* Session::set() overrides DBO::set() in order
* to support transparently assigning information
* to the session itself.
*/
public function set($key, $value) {
if ($key == 'id') {
return false;
} else if ($key == 'user') {
$this->fields['user'] = $value;
} else {
$this->session[$key] = $value;
}
return true;
}
/**
* Since the primary key value comes from the request
* itself (via the session in the browser), Session::load
* should offer a way of automatically handling this.
*/
public function load() {
return parent::load($this->fields[$this->pk]);
}
/**
* Override the contructor in order to create the reference
* to the $_SESSION superglobal.
*/
public function __construct() {
global $_SESSION;
parent::__construct();
$this->session = $_SESSION;
}
}