PHP: overlaying the $ _SESSION variable

Since I noticed that this is a template that I constantly reprogrammed, I created a DataContainer class that overrides __set , __get , __isset , __unset and implements ArrayAccess , Countable , IteratorAggregate and Serializable

For example, my View class, which displays PHP templates in MVC style, inherits from a DataContainer so that it overloads access to the data that is passed to the template.

Now I find that I want to create a Session class to abstract from working with a low-level PHP session. It seemed to me that this session class will do almost everything that the DataContainer does, but in fact - the DataContainer - it contains the data.

However, if I inherit the DataContainer, then all overloaded calls go into its private $_data . Of course, I can override the methods of the DataContainer public get($key) , public set($key,$val) , etc., but the only thing I would like to do is rename $this->_data to $_SESSION .

Is it possible to set a variable as a reference to a special global such as $_SESSION ?

 class Session extends DataContainer { //singleton stuff private function __construct() { $this->_data =& $_SESSION; } } 

Is that even a good idea? If not, what do you suggest?

+4
source share
2 answers

Is it possible to set a variable as a reference to a special global $ _SESSION?

Yes, $this->_data =& $_SESSION;

Is that even a good idea?

I don’t understand why not, it can be argued that it is better to pass data to the constructor by reference so that it can be used for any array, and not just for the session.

So yes.

edit: as a side point, remember that you do not always have a session, sometimes your launch on Kli, etc., personally I have my own session object (just such a DataContainer as yours), which I then save in $ _SESSION where necessary, or a file or .. - i.e. I am storing (stateful) session objects in $ _SESSION, rather than using $ _SESSION as session data, if that makes sense.

+1
source

I hope this is a good idea as I use it all the time. Decorator view, for container variable only. Yes, it has been working for about 3 years, and I really like the verification and tracking capabilities it provides for more complex projects. Keep in mind that you cannot force any other code to use the container instead of $_SESSION , but a wide-ranging project search for this particular line gives quick results when most of the code uses other means.

I also do this Singleton for those times when projects are not suitable for the right path of dependency injection, be it size, time, or historical reasons. The link to Session::instance() about as simple as supgllobal $_SESSION .

+1
source

Source: https://habr.com/ru/post/1316595/


All Articles