/**
file:MEMSession.class.php Session的数据库驱动,将会话信息自定义到数据库中
需要指定php.ini 中 session.save_handler 改为user
*/
class MEMSession{
const NS = 'session_'; //声明一个memcached前缀,防止冲突
protected static $mem=null; //声明一个处理器,使用MemCache处理Session信息
protected static $lifetime=null; //声明Session的生存周期
public static function start(Memcache $mem){
self::$mem=$mem;
self::$lifetime=ini_get('session.gc_maxlifetime'); //默认是1440秒,24分钟
/* 在php.ini中设置session.save_handler的值为"user"时被系统调用,开始调用每个声明周期过程*/
/* 因为是回调类中的静态方法作为参数,所以每个参数需要使用数组指定静态方法所在的类*/
session_set_save_handler(array(__CLASS__,'open'), array(__CLASS__,'close'), array(__CLASS__,'read'), array(__CLASS__,'write'), array(__CLASS__,'destroy'), array(__CLASS__,'gc'));
session_start(); //这也是必须的,打开session,必须在session_set_save_handler后面执行
}
//called by session_start( )
private static function open($path,$name){
return true;
}
//called at page end
public static function close(){
return true;
}
//called after session_start( )
private static function read($sid){
//通过key从memcached中获取氮气用户的Session数据
$out=self::$mem->get(self::session_key($sid));
if($out===false||$out===null){
return "";
}
return $out;
}
//called when session data is to be written
public static function write($sid,$data){
//将数据写入memcached服务器中
$method=$data?"set":"replace"; //$data值为空则通过replace替换
return self::$mem->$method(self::session_key($sid),$data,MEMCACHE_COMPRESSED,self::$lifetime);
}
//called by session_destroy( )
public static function destroy($sid){
//销毁在memcached中存储的指定的用户会话数据
return self::$mem->delete(self::$session_key($sid));
}
//called randomly
private static function gc($lifetime){
return true;
}
/**
* 用于组成$sid在memcache中的key
* @param string $sid 为当前用户的SessionId
* @return $session_key 指定前缀后的memcached的key
*/
private static function session_key($sid){
$session_key="";
if(defined('PROJECT_NS')) //defined检查常量是否存在
$session_key .= PROJECT_NS;
$session_key .= self::NS . $sid;
return $session_key;
}
}
测试:
<?php
/* 加载自定义Session的memcached 存储方式类型MEMSession信息的过程 */
require "MEMSession.class.php";
//创建Memcache类的对象
$mem=new Memcache;
//添加Memcached服务器,可以添加多个做分布式
$mem->addServer("localhost",11211);
//$mem->addServer()
//使用MEMSession中静态方法start(),并传递memcache类对象,使用自定义memcached的Session处理的方式
MEMSession::start($mem);
//向$_SESSION变量中存和取一个数据,演示自定义memcached方式是否可用
$_SESSION['username']="admin";
echo $_SESSION['username'];
//echo "who";