不說廢話, 直接上代碼。
<?php
class MCache extends Object implements CacheFace
{
private $mem = null; //Mem對象
private $sId = 1; //servier服務ID
/**
* 初始化Memcache
*
* @return Object
*/
public function __construct()
{
if ( !class_exists('Memcache') )
{
throw new QException('PHP extension does not exist: Memcache');
}
$this->mem = new Memcache();
}
/**
* 鏈接memcahce服務
*
* @access private
* @param string $key 關鍵字
* @param string $value <a href="http://www.php1.cn/category/79.html">緩存</a>內容
* @return array
* @update http://www.lai18.com
*/
private function connect( $sid )
{
$file = $this->CacheFile();
require $file;
if(! isset($cache) )
{
throw new QException('<a href="http://www.php1.cn/category/79.html">緩存</a>配置文件不存在'.$file);
}
$server = $cache[$this->cacheId];
$sid = isset($sid) == 0 ? $this->sId : $sid;//memcache服務選擇
if ( ! $server[$sid])
{
throw new QException('當前操作的<a href="http://www.php1.cn/category/79.html">緩存</a>服務器配置文件不存在');
}
$host = $server[$sid]['host'];
$port = $server[$sid]['port'];
try {
$this->mem->connect( $host , $port );
} catch (Exception $e) {
exit('memecache連接失敗,錯誤信息:'. $e->getMessage());
}
}
/**
* 寫入<a href="http://www.php1.cn/category/79.html">緩存</a>
*
* @access private
* @param string $key 關鍵字
* @param string $value <a href="http://www.php1.cn/category/79.html">緩存</a>內容
* @return array
*/
public function set( $key , $value , $sid , $expire = 0)
{
$data = $this->get($key , $sid); //如果已經存在key值
if( $data )
{
return $this->mem->set( $key , $value ,MEMCACHE_COMPRESSED , $expire);
} else {
return $this->mem->add( $key , $value ,MEMCACHE_COMPRESSED , $expire);
}
}
/**
* 讀取<a href="http://www.php1.cn/category/79.html">緩存</a>
*
* @access private
* @param string $key 關鍵字
* @param int $sid 選擇第幾臺memcache服務器
* @return array
*/
public function get( $key , $sid)
{
$this->connect( $sid );
return $this->mem->get($key);
}
/**
* 清洗(刪除)已經存儲的所有的元素
*
* @access private
* @return array
*/
public function flush()
{
$this->connect();
return $this->mem->flush();
}
/**
* 刪除<a href="http://www.php1.cn/category/79.html">緩存</a>
*
* @access private
* @param string $key 關鍵字
* @param int $sid 選擇第幾臺memcache服務器
* @return array
*/
public function remove( $key , $sid)
{
$this->connect();
return $this->mem->delete($key);
}
/**
* 析構函數
* 最後關閉memcache
*/
public function __destruct()
{
/*if(! $this->mem)
{
$this->mem->close();
}*/
}