Created
May 12, 2016 20:53
-
-
Save DanyHenriquez/ea08d9ced419fe48ef690ab462857661 to your computer and use it in GitHub Desktop.
Php7 MongoDB session handler.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MongoSessionHandler implements \SessionHandlerInterface | |
{ | |
public $client; | |
public $database; | |
public $collection; | |
public function __construct($uri, $uriOptions = [], $driverOptions = []) | |
{ | |
$this->client = new \MongoDB\Client($uri, $uriOptions, $driverOptions); | |
} | |
public function withDatabase($database) | |
{ | |
$new = clone $this; | |
$new->database = $database; | |
return $new; | |
} | |
public function withCollection($collection) | |
{ | |
$new = clone $this; | |
$new->collection = $collection; | |
return $new; | |
} | |
public function open($savePath, $sessionName) | |
{ | |
return true; | |
} | |
public function close() | |
{ | |
return true; | |
} | |
public function read($id) | |
{ | |
return $this | |
->client | |
->{$this->database} | |
->{$this->collection} | |
->findOne(['sessionId' => $id]) | |
->data; | |
} | |
public function write($id, $data) | |
{ | |
$this->destroy($id); | |
$this | |
->client | |
->{$this->database} | |
->{$this->collection} | |
->insertOne(['sessionId' => $id, 'data' => $data, 'createdAt' => time()]); | |
return true; | |
} | |
public function destroy($id) | |
{ | |
$this | |
->client | |
->{$this->database} | |
->{$this->collection} | |
->deleteOne(['sessionId' => $id]); | |
return true; | |
} | |
public function gc($maxlifetime) | |
{ | |
foreach ($this->client->{$this->database}->{$this->collection}->find() as $session) { | |
if ($session->createdAt + $maxlifetime < time()) { | |
$this | |
->client | |
->{$this->database} | |
->{$this->collection} | |
->deleteOne(['sessionId' => $session->sessionId]); | |
} | |
} | |
return true; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$sessionHandler = (new \System\MongoSessionHandler('mongodb://localhost:27017')) | |
->withDatabase('session') | |
->withCollection('session'); | |
session_set_save_handler($sessionHandler, true); | |
session_start(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment