<?php
if(!defined('R_P'))  die("access die");
class cache{
	static $_instance = array();
	static $_status = array();
	static $_timeout = 2;
	function instance($key){
		$config = self::_get_config();
		if(empty($config)) die("please modify the file -- config/config.php");
		$index = intval($key) % count($config);
		if(!isset(self::$_instance[$index]) || is_resource(self::$_instance[$index]) === false){
			if(isset(self::$_status[$index]) && self::$_status[$index] === false) return self::$_instance[$index];
			self::$_instance[$index] = new Memcache;
			self::$_status[$index] = self::$_instance[$index]->connect($config[$index]['host'], $config[$index]['port'], self::$_timeout);
		}
		return self::$_instance[$index];
	}
	
	function get($key){
		$key = self::_hash($key);
		return self::instance($key)->get($key);
	}
	
	function delete($key){
		$key = self::_hash($key);
		return self::instance($key)->delete($key);
	}
	
	function set($key, $val, $time){
		$key = self::_hash($key);
		return self::instance($key)->set($key, $val, MEMCACHE_COMPRESSED, $time);
	}	

	function flush(){
		$config = self::_get_config();
		foreach($config as $val){
			$mem = new Memcache;
			$mem->connect($val['host'], $val['port'], 5);
			$mem->flush();
		}
		return true;
	}	
	
	function _hash($k){
		return (string)sprintf("%u", crc32($k));
	}	
	
	function _get_config(){
		global $_SET;
		return $_SET['memcached'];
	}
}
?>