Because I noticed it was a pattern I was constantly re-implementing, I made a DataContainer class that overrides __set,__get,__isset,__unset, and implements ArrayAccess, Countable, IteratorAggregate, and Serializable
For example, my View class, which renders PHP templates in an MVC fashion, inherits from DataContainer so that it has overloaded access to the data that gets supplied to the template.
Now, I am finding myself wanting to create a Session class to abstract away from PHP’s low-level session handling. It occured to me that this Session class would do just about everything DataContainer does, and in fact, is-a DataContainer – it holds data.
However, if I inherit from DataContainer, then all the overloaded calls go to its private $_data array. Of course, I can override DataContainer’s public get($key), public set($key,$val), etc methods, but the only thing I would be doing is renaming $this->_data to $_SESSION.
Is it possible to set a variable as a reference to a special global like $_SESSION?
class Session extends DataContainer {
//singleton stuff
private function __construct() {
$this->_data =& $_SESSION;
}
}
Is it even a good idea to do this? If not, what do you suggest?
Yes,
$this->_data =& $_SESSION;I don’t see why not, one could argue that it may be better to pass the data in to the constructor by reference so that it can be used for any array not just session.
Thus, Yes.
edit: as a side point, remember you don’t always have a session, sometimes your running on cli etc, personally I have my own session object (just a DataContainer like yours) which I then persist to $_SESSION where needed, or file or.. – ie I save (stateful) session objects in the $_SESSION rather than use the $_SESSION as the session data, if that makes sense..