<?php

class Cache_Memcache extends Memcache
{
	public $host_id=null;
	protected static $instance;
	
	static function i()
	{
		return self::instance();
	}
	
	static function instance()
	{
		if (self::$instance === null)
		{
			self::$instance = new self;
		}
		return self::$instance;
	}
	
	private function __clone() {}

	function __construct()
	{
		$this->host_id=LabConfig::$cfg['host_id'];
		$this->_cache_compress = (LabConfig::$cfg["memcached_compress"]) ? MEMCACHE_COMPRESSED : 0;
		$this->connect(LabConfig::$cfg["memcached_host"], LabConfig::$cfg["memcached_port"]);
	}
	
	function set($key, $data, $ttl=3600)
	{
		if ($ttl==-1) $ttl=0; //в мемкэше 0 соответсвует бессрочному хранению
		if ($ttl) $ttl=time()+$ttl;
		return parent::set($this->_getKey($key), $data, $this->_cache_compress, $ttl);
	}
	
	function remove($key)
	{
		$this->delete($this->_getKey($key));
	}
	
	function clean()
	{
		$this->flush();
	}
	
	function get($key)
	{
		$result=parent::get($this->_getKey($key));
		return $result;
		//return $result?$result:false;
	}
	
	protected function _getKey($key)
	{
		if (empty($this->host_id)) return $key;
		else
		{
			foreach((array)$key as $k=>$v)
			{
				$key[$k]=$this->host_id.'_'.$v;
			}
			return $key;
		}
	}
}