Sessions in PHP5 - embedded sessions or not?

Background:
I am at the initial stage of a new project built on PHP5.3. I was just starting to learn how to handle sessions in a way that initially allowed me to store sessions in a database. I am separating all session management into a separate library to facilitate transparent migration to memcached, a separate session database server, or something else the best solution by then.

I am a little confused about what would be a good approach, although there are many different ideas on the Internet about how to handle sessions depending on the version of PHP, and the more I read, the more I get embarrassed.

Question:
Here are the options that I think are most suitable. Which should I use and why? Are there other alternatives to consider?

Option 1:
Using session_set_save_handler and create custom functions for each session event in order to make full use of the built-in (built-in) processing of PHP sessions, but still save the sessions in the database. The session will be written as $_SESSION['identifier'] = 'value'; .

Option 2:
Building a complete session class that has nothing to do with PHP sessions and just acts like any database model that talks to the sessions table in my database. The session will be written as $this->sessions->write('identifier', 'value'); .

+4
source share
2 answers

I suggest you go the last route, but with a sharp turn.

Create a Session class, then use the adapter template to extend it with the DatabaseSession and CookieSession specific classes.

Overriding session_save_handler just seems too strong due to my honest opinion.

Routing the entire session interaction through your wrapper class gives you more flexibility as the project gets larger.

Something like that:

 interface SessionAdaptor { function write($key, $data, $timeout); function read($key); function key_exists($key); } class Session { private $adaptor; function __construct(SessionAdaptor $adaptor) { $this->adaptor = $adaptor; } //here we go: function write($key, $data, $timeout) { return $this->adaptor->write($key, $data, $timeout); } function read($key) { return $this->adaptor->read($key); } function key_exists($key) { return $this->adaptor->key_exists($key); } } class DatabaseSession implements SessionAdaptor { //... } class CookieSession implements SessionAdaptor { //... } 

Using:

 $database_session = new Session(new DatabaseSession()); 
+2
source

Superglobal $_SESSION is actually a pretty good feature in PHP.

Depending on what your software solution will be, third-party users will be more used to writing and reading from this superglobal with your custom session handlers doing magic in the background.

There are also good security enhancements available from Suhosin that you don’t have to worry about when developing a session repository for yourself.

+8
source

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


All Articles