<?php
/**
  * @method 缓存类，优先memcache=>file
  * @author soul
  * @copyright 2016/3/31
  */
class LibMemcache
{
	private $memType = null;
	private $memcache = null;
	private $memFile = null;

	public function __construct()
	{
		if(!empty(mvc::$cfg['MEMCACHE']['mem']))
		{
			$this->memcache = new Memcached();
			foreach(mvc::$cfg['MEMCACHE']['mem'] as $host)
			{
				$res = $this->memcache->addServer($host['host'], $host['port']);
				if(!$res)
				{
					$this->memType = null;
					break;
				}
				$this->memType = 'mem';
			}
		}
		if(!$this->memType){
			$this->memFile = mvc::$cfg['MEMCACHE']['file'];
			$this->memType = 'file';
		} 
	}

	/**
	  * @method 获取文件缓存的内容
	  * @param  $key
	  * @author soul
	  * @copyright 2016/3/30
	  */
	private function getMemFile()
	{
		$dataArr = [];
		if($dataArr = @file_get_contents($this->memFile))
			$dataArr = unserialize($dataArr);
		return $dataArr;
	}

	/**
	  * @method 保存文件缓存的内容
	  * @param  $key
	  * @author soul
	  * @copyright 2016/3/30
	  */
	private function saveMemFile($dataArr)
	{
		@file_put_contents($this->memFile, serialize($dataArr));
	}

	/**
	  * @method 获取数据
	  * @param  $key
	  * @author soul
	  * @copyright 2016/3/30
	  */
	public function get($key)
	{
		switch($this->memType)
		{
			case 'mem':
				return $this->memcache->get($key);
			break;
			case 'file':
				$dataArr = $this->getMemFile();
				return $dataArr[$key];
			break;
		}
	}
	

	/**
	  * @method 添加或者修改
	  * @param  $key
	  * @param  $value
	  * @author soul
	  * @copyright 2016/3/30
	  */
	public function set($key, $value)
	{
		switch($this->memType)
		{
			case 'mem':
				$res = $this->memcache->set($key, $value, 3600*2);
				if(!$res)
				{
					$this->memcachereplace($key, $value, 3600*2);
				}
			break;
			case 'file':
				$dataArr = $this->getMemFile();
				$dataArr[$key] = $value;
				$this->saveMemFile($dataArr);
			break;
		}
	}


	/**
	  * @method 删除数据
	  * @param  $key
	  * @author soul
	  * @copyright 2016/3/30
	  */
	public function del($key)
	{
		switch($this->memType)
		{
			case 'mem':
				return $this->memcache->delete($key);
			break;
			case 'file':
				$dataArr = $this->getMemFile();
				unset($dataArr[$key]);
				$this->saveMemFile($dataArr);
			break;
		}
	}

	/**
	  * @method 清空缓存
	  * @author soul
	  * @copyright 2016/3/30
	  */
	public function clear()
	{
		switch($this->memType)
		{
			case 'mem':
				return $this->memcache->flush();
			break;
			case 'file':
				@unlink($this->memFile);
			break;
		}
	}
}