<?php

/**
 *--------------------------------------
 * memcache缓存
 *--------------------------------------
 * @project		: pfa
 * @author		: cblee
 * @created		: 2012-9-24
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class CacheMemcache extends Cache
{
	/* 构造函数 */
	function __construct($options = array())
	{
		if(!extension_loaded('memcache'))
		{
			halt(L('_NOT_SUPPERT_').':memcache');
		}
		$this->options = array(
			'host' => C('CACHE.MEMCACHE_HOST'),
			'port' => C('CACHE.MEMCACHE_PORT'),
			'timeout' => C('CACHE.MEMCACHE_TIMEOUT'),
			'persistent' => false,
			'expire' => C('CACHE.EXPIRE'),
			'length' => 0,
		);
		if(!empty($options))
		{
			$this->options = array_merge($this->options, $options);
		}
		$func = $options['persistent'] ? 'pconnect' : 'connect';
		$this->handler = new Memcache;
		$this->connected = $options['timeout'] === false ?
			$this->handler->$func($options['host'], $options['port']) :
			$this->handler->$func($options['host'], $options['port'], $options['timeout']);
	}

	/* 是否连接 */
	private function is_connected()
	{
		return $this->connected;
	}

	/* 读取缓存 */
	public function get($name)
	{
		N('cache_read', 1);
		return $this->handler->get($name);
	}

	/* 写入缓存 */
	public function set($name, $value, $expire = null)
	{
		N('cache_write', 1);
		if(is_null($expire))
		{
			$expire = $this->options['expire'];
		}
		if($this->handler->set($name, $value, 0, $expire))
		{
			return true;
		}
		return false;
	}

	/* 删除缓存 */
	public function del($name, $ttl = false)
	{
		return $ttl === false ?
			$this->handler->delete($name) :
			$this->handler->delete($name, $ttl);
	}

	/* 清除缓存 */
	public function clear()
	{
		return $this->handler->flush();
	}
}

?>