<?php
/**
 * Memcache缓存类
 * 直接通过静态方法调用
 * @author wj45 <j@wj45.net>
 */
class cache {
	private static $_mem;

	//禁止实例化
	private function __construct() {}
	
	public static function conn() {
		if ( is_object(self::$_mem) ) {
			return true;  //避免重复链接
		}
		if( !defined('MEMCACHE_HOST') ) {
			define('MEMCACHE_HOST', '127.0.0.1:11211');
		}
		$memcache = explode(':', MEMCACHE_HOST);
		$host = isset($memcache[0]) ? $memcache[0] : '127.0.0.1';
		$port = isset($memcache[1]) ? $memcache[1] : '11211';
		self::$_mem = new Memcache;
		self::$_mem->connect($host, $port);
	}
	
	/**
	 * 保存
	 * @parame string $key 缓存名称
	 * @parame unkown $var 要缓存的数据
	 * @parame int $expire 缓存有效期，0为始终有效
	 */
	public static function set( $key, $var) {
		self::conn();
		$expire = cacheTime*60;
		$rs = self::$_mem->set($key, $var, 0, $expire);
		return $rs;
	}
	
	/**
	 * 读取
	 */
	public static function get( $key ) {
		self::conn();
		$rs = self::$_mem->get($key);
		return $rs;
	}
	
	/**
	 * 删除
	 */
	public static function delete( $key ) {
		self::conn();
		$rs = self::$_mem->delete($key);
		return $rs;
	}
	
	/**
	 * 清除所有数据
	 */
	public static function flush() {
		self::conn();
		if ( !is_object(self::$_mem) ) {
			return true;
		}
		self::$_mem->flush();
	}
	
	/**
	 * 关闭连接
	 */
	public static function close() {
		self::conn();
		if ( !is_object(self::$_mem) ) {
			return true;
		}
		self::$_mem->close();
	}
}
?>