PHP: aliasing the $_SESSION variable
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 varia开发者_运维问答ble 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?
Is it possible to set a variable as a reference to a special global like $_SESSION?
Yes, $this->_data =& $_SESSION;
Is it even a good idea to do this?
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..
I sure hope it's good idea, as I use it constantly. Kind of a Decorator
, only for a variable-container. Yes, it has worked for for about 3 years now, and I very much like the validating & tracing capabilities it yields on more complex projects. Keep in mind you cannot force any other code to use the container instead of $_SESSION
, but a project wide search for that particular string yields fast results when the majority of the code uses other means.
I also make it a Singleton
for those moments a projects is not suited for a proper dependancy-injection path, either for size, time or historical reasons. Referencing a Session::instance()
is about as easy as the $_SESSION
superglobal.
精彩评论