Skip to content

Instantly share code, notes, and snippets.

@daschl
Created June 25, 2012 06:15
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daschl/2986942 to your computer and use it in GitHub Desktop.
Save daschl/2986942 to your computer and use it in GitHub Desktop.
A reference implementation of a Couchbase Session Handler with PHP
<?php
/**
* A reference implementation of a custom Couchbase session handler.
*/
class CouchbaseSessionHandler implements SessionHandlerInterface {
/**
* Holds the Couchbase connection.
*/
protected $_connection = null;
/**
* The Couchbase host and port.
*/
protected $_host = null;
/**
* The Couchbase bucket name.
*/
protected $_bucket = null;
/**
* The prefix to be used in Couchbase keynames.
*/
protected $_keyPrefix = 'session:';
/**
* Define a expiration time of 10 minutes.
*/
protected $_expire = 600;
/**
* Set the default configuration params on init.
*/
public function __construct($host = '127.0.0.1:8091', $bucket = 'default') {
$this->_host = $host;
$this->_bucket = $bucket;
}
/**
* Open the connection to Couchbase (called by PHP on `session_start()`)
*/
public function open($savePath, $sessionName) {
$this->_connection = new Couchbase($this->_host, $this->_bucket);
return $this->_connection ? true : false;
}
/**
* Close the connection. Called by PHP when the script ends.
*/
public function close() {
unset($this->_connection);
return true;
}
/**
* Read data from the session.
*/
public function read($sessionId) {
$key = $this->_keyPrefix . $sessionId;
$result = $this->_connection->get($key);
return $result ?: null;
}
/**
* Write data to the session.
*/
public function write($sessionId, $sessionData) {
$key = $this->_keyPrefix . $sessionId;
if(empty($sessionData)) {
return false;
}
$result = $this->_connection->set($key, $sessionData, $this->_expire);
return $result ? true : false;
}
/**
* Delete data from the session.
*/
public function destroy($sessionId) {
$key = $this->_keyPrefix . $sessionId;
$result = $this->_connection->delete($key);
return $result ? true : false;
}
/**
* Run the garbage collection.
*/
public function gc($maxLifetime) {
return true;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment