rn $this;
}
/**
* 清空所有缓存
*
* @return Cache_File
*/
public function clear() {
// 遍历目录清除缓存
$cacheDir = $this->_cachesDir;
$d = dir($cacheDir);
while(false !== ($entry = $d->read())) {
if(''.'' == $entry[0]) {
continue;
}
$cacheEntry = $cacheDir . ''/'' . $entry;
if(is_file($cacheEntry)) {
@unlink($cacheEntry);
} elseif(is_dir($cacheEntry)) {
// 缓存文件夹有两级
$d2 = dir($cacheEntry);
while(false !== ($entry = $d2->read())) {
if(''.'' == $entry[0]) {
continue;
}
$cacheEntry .= ''/'' . $entry;
if(is_file($cacheEntry)) {
@unlink($cacheEntry);
}
}
$d2->close();
}
}
$d->close();
return $this;
}
}
/**
* 缓存单元的数据结构
* array(
* ''time'' => time(), // 缓存写入时的时间戳
* ''expire'' => $expire, // 缓存过期时间
* ''valid'' => true, // 缓存是否有效
* ''data'' => $value // 缓存的值
* );
*/
final class Cache {
/**
* 缓存过期时间长度(s)
*
* @var int
*/
private
PHP 缓存实现代码及详细注释_网学
浏览:
expire = 3600;
/**
* 缓存处理类
*
* @var Cache_Abstract
*/
private
PHP 缓存实现代码及详细注释_网学
浏览:
storage = null;
/**
* @return Cache
*/
static public function createCache($cacheClass = ''Cache_File'') {
return new self($cacheClass);
}
private function __construct($cacheClass) {
$this->_storage = new $cacheClass();
}
/**
* 设置缓存
*
* @param string $key
* @param mixed $value
* @param int $expire
*/
public function set($key, $value, $expire = false) {
if (!$expire) {
$expire = $this->_expire;
}
$this->_storage->checkLock($key);
$data = array(''time'' => time(), ''expire'' => $expire, ''valid'' => true, ''data'' => $value);
$this->_storage->lock($key);
try {
$this->_storage->store($key, $data);
$this->_storage->unlock($key);
} catch (CacheException $e) {
$this->_storage->unlock($key);
throw $e;
}
}
/**
* 读取缓存
*
* @param string $key
* @return mixed
*/
public function get($key) {
$data = $this->fetch($key);
if ($data && $data[''valid''] && !$data[''isExpired'']) {
return $data[''data''];
}
return false;
}
/**
* 读缓存,包括过期的和无效的,取得完整的存贮结构
*
* @param string $key
*/
public function fetch($key) {
$this->_storage->checkLock($key);
$data = $this->_storage->fetch($key);
if ($data) {
$data[''isExpired''] = (time() - $data[''time'']) > $data[''expire''] ? true : false;
return $data;
}
return false;
}
/**
* 删除缓存
*
* @param string $key
*/
public function delete($key) {
$this->_storage->checkLock($key)
->lock($key)
->delete($key)
->unlock($key);
}
public function clear() {
$this->_storage->clear();
}
/**
* 把缓存设为无效
*
* @param string $key
*/
public function setInvalidate($key) {
$this->_storage->checkLock($key)
->lock($key);
try {
$data = $this->_storage->fetch($key);
if ($data) {
$data[''valid''] = false;
$this->_storage->store($key, $data);
}
$this->_storage->unlock($key);
} catch (CacheException $e) {
$this->_storage->unlock($key);
throw $e;
}
}
/**
* 设置缓存过期时间(s)
*
* @param int $expire
*/
public function setExpire($expire) {
$this->_