<?php
/* * *********************************************************
 * [cml] (C)2012 - 3000 cml http://linhecheng.com
 * @Author  linhecheng<linhechengbush@live.com>
 * @Date: 13-6-26 上午11:23
 * @version  1.0 
 * cml框架 memcache缓存驱动
 * *********************************************************** */

defined('CML_PATH') || exit();

import('CacheBase',CML_LIB_DRIVER_PATH.DIR_SEP.'Cache'.DIR_SEP, '.class.php');
class CacheMemcache extends CacheBase
{
	/**
	* @var bool|array
	*/
	private $conf;

	/**
	* @var CacheMemcache
	*/
	private $memcache;

	/**
	 * @param bool $conf
	 */
	public function __construct($conf = false)
	{
		$this->conf = $conf ? $conf : C('CACHE');

		if(extension_loaded('Memcached')) {
			$this->memcache = new Memcached;
		} else if(extension_loaded('Memcache')) {
			$this->memcache = new Memcache;
		} else {
			throw_exception(L('_CACHE_EXTEND_NOT_INSTALL_', null, 'Memcache'));
		}		

		if(!$this->memcache) {
			throw_exception(L('_CACHE_EXTEND_NOT_ON_', null, 'Memcache'));
		}

		if(!$this->conf['MORE_SERVER']) { //单台
			if(!$this->memcache->connect($this->conf['HOST'], $this->conf['PORT'])) {
				throw_exception(L('_CACHE_CONNECT_FAIL_', null, 'Memcache'));
			}
		} else { //多台
			$this->memcache->addServer($this->conf['HOST'], $this->conf['PORT'], false);
			foreach($this->conf['MORE_SERVER'] as $val) {
				$this->memcache->addServer($val['HOST'], $val['PORT'], false); //增加服务器
			}
		}

	}

	/**
	 * 根据key取值
	 *
	 * @param $key
	 *
	 * @return mixed
	 */
	public function get($key)
	{
		$data = array();
		if(is_array($key)) {
			foreach($key as $k) {
				$arr = $this->memcache->get($this->conf['PREFIX'] . $k);
				$data[$k] = $arr;
			}			
		} else {
			$data = $this->memcache->get($this->conf['PREFIX'] . $key);
		}
		return $data;
	}

	/**
	 * 存储对象
	 *
	 * @param $key
	 * @param $value
	 * @param int $expire
	 *
	 * @return bool
	 */
	public function set($key, $value, $expire = 0)
	{
		return $this->memcache->set($this->conf['PREFIX'] . $key, $value, false, $expire);
	}

	/**
	 * 更新对象
	 *
	 * @param $key
	 * @param $value
	 * @param int $expire
	 *
	 * @return bool
	 */
	public function update($key, $value, $expire = 0)
	{
		$this->memcache->replace($this->conf['PREFIX'] . $key, $value, false, $expire);
	}

	/**
	 * 删除对象
	 *
	 * @param $key
	 *
	 * @return bool
	 */
	public function delete($key)
	{
		return $this->memcache->delete($this->conf['PREFIX'] . $key);
	}

	/**
	 * 清洗已经存储的所有元素
	 *
	 */
	public function truncate()
	{
		$this->memcache->flush();
		return true;
	}

	/**
	 * 自增
	 *
	 * @param $key
	 * @param int $val
	 *
	 * @return bool
	 */
	public function increment($key, $val = 1)
	{
		$this->memcache->increment($this->conf['PREFIX'] . $key, $val);
	}

	/**
	 * 自减
	 *
	 * @param $key
	 * @param int $val
	 *
	 * @return bool
	 */
	public function decrement($key, $val =1)
	{
		$this->memcache->decrement($this->conf['PREFIX'] . $key, $val);
	}

}