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

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

import('CacheBase',CML_LIB_DRIVER_PATH.DIR_SEP.'Cache'.DIR_SEP, '.class.php');
class CacheApc extends CacheBase
{
	public function __construct($conf = false)
	{
		if (!function_exists('apc_cache_info')) {
			throw_exception(L('_CACHE_EXTENT_NOT_INSTALL_', null, 'Apc'));
		}
		$this->conf = $conf ? $conf : C('CACHE');
	}

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

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

	/**
	 * 更新对象
	 *
	 * @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 apc_delete($this->conf['PREFIX'] . $key);
	}

	/**
	 * 清洗已经存储的所有元素
	 *
	 */
	public function truncate()
	{
		return apc_clear_cache('user'); //只清除用户缓存
	}

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

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

}