<?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 CacheRedis extends CacheBase
{
	/**
	 * @var bool|array
	 */
	private $conf;

	/**
	 * @var CacheRedis
	 */
	private $redis;

	public function __construct($conf = false)
	{
		$this->conf = $conf ? $conf : C('CACHE');

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

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

		if(!$this->redis->connect($this->conf['HOST'], $this->conf['PORT'])) {
			throw_exception(L('_CACHE_CONNECT_FAIL_', null, 'Redis'));
		}
	}

	/**
	 * 根据key取值
	 *
	 * @param $key
	 *
	 * @return mixed
	 */
	public function get($key)
	{
		$result = $this->redis->get($this->conf['PREFIX'] . $key);
		return json_decode($result, true);
	}

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

	/**
	 * 更新对象
	 *
	 * @param $key
	 * @param $value
	 * @param int $expire
	 *
	 * @return bool|int
	 */
	public function update($key, $value, $expire = 0)
	{
		$arr = $this->get($key);
		if(!empty($arr)) {
			$arr = array_merge($arr, $value);
			return $this->set($key, $arr, $expire);
		}
		return 0;
	}

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

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

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

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

	/**
	 * 判断key值是否存在
	 *
	 * @param $key
	 * @return mixed
	 *
	 * @return bool
	 */
	public function exists($key)
	{
		return $this->redis->exists($this->conf['PREFIX'] . $key);
	}

	//为了方便使用未封装的redis的其它方法
	public function redis()
	{
		return $this->redis;
	}

}