nicktacular / php-mongo-session

A PHP session handler with a Mongo DB backend.
MIT License
18 stars 6 forks source link

Saving data in json format instead of binary #4

Closed salvador-dali closed 10 years ago

salvador-dali commented 10 years ago

I am trying to modify your class to save data in json format instead of binary. So I tried to modify https://github.com/nicktacular/php-mongo-session/blob/master/MongoSession.php#L385 to

return json_decode($this->sessionDoc['data']);

and https://github.com/nicktacular/php-mongo-session/blob/master/MongoSession.php#L418 to $this->sessionDoc['data'] = json_encode($_SESSION);

The problem that this clears the session data (basically does not work). Is there a way to save data in json format?

nicktacular commented 10 years ago

The issue is that the read method must return a string that is formatted in the exact same way that PHP gives it to you in write. No modification can occur and and you should make no assumptions about the format. That is why I've chosen to save as binary since there's no data sequence that will throw an exception when it's headed for Mongo.

I recommend that you see what types of data PHP is calling the write method with and you'll see why what you're proposing won't work. The $data in write is already serialized and you cannot access $_SESSION inside your handler since this is something that PHP takes care of (handler -> PHP -> $_SESSION).

If you want to customize your access to the $_SESSION you should be writing a wrapper class that takes care of this for you. A really simple and crude example is as follows:

class MySession {
  public function __get($key)
  {
    if (isset($_SESSION[$key]) {
      //if you want a special format, you would do something to it here
      return $_SESSION[$key];
  }

}

$mysess = new MySession();
var_dump($mysess->hello);

This is only to illustrate that the reading from the session should be encapsulated in some sort of object and you shouldn't really be trying to access $_SESSION directly. This is also not a concern of the session handler since it is only meant to be interacted with from PHP directly (not the developer).