. ''_'' . $key;
}
}
/**
* 文件缓存实现
*
*
* @category Mjie
* @package Cache
* @author 流水孟春
* @copyright Copyright (c) 2008- <cmpan(at)qq.com>
* @license New BSD License
* @version $Id: Cache/File.php 版本号 2010-04-18 16:46 cmpan $
*/
class Cache_File extends Cache_Abstract {
protected
PHP 缓存实现代码及详细注释_网学
浏览:
cachesDir = ''cache'';
public function __construct() {
if (defined(''DATA_DIR'')) {
$this->_setCacheDir(DATA_DIR . ''/cache'');
}
}
/**
* 获取缓存文件
*
* @param string $key
* @return string
*/
protected function _getCacheFile($key) {
return $this->_cachesDir . ''/'' . substr($key, 0, 2) . ''/'' . $key . ''.php'';
}
/**
* 读取缓存变量
* 为防止信息泄露,缓存文件格式为php文件,并以"<?php exit;?>"开头
*
* @param string $key 缓存下标
* @return mixed
*/
public function fetch($key) {
$cacheFile = self::_getCacheFile($key);
if (file_exists($cacheFile) && is_readable($cacheFile)) {
return unserialize(@file_get_contents($cacheFile, false, NULL, 13));
}
return false;
}
/**
* 缓存变量
* 为防止信息泄露,缓存文件格式为php文件,并以"<?php exit;?>"开头
*
* @param string $key 缓存变量下标
* @param string $value 缓存变量的值
* @return bool
*/
public function store($key, $value) {
$cacheFile = self::_getCacheFile($key);
$cacheDir = dirname($cacheFile);
if(!is_dir($cacheDir)) {
if(mkdir($cacheDir" target="_blank">!@mkdir($cacheDir, 0755, true)) {
throw new CacheException("Could not make cache directory");
}
}
return @file_put_contents($cacheFile, ''<?php exit;?>'' . serialize($value));
}
/**
* 删除缓存变量
*
* @param string $key 缓存下标
* @return Cache_File
*/
public function delete($key) {
if(emptyempty($key)) {
throw new CacheException("Missing argument 1 for Cache_File::delete()");
}
$cacheFile = self::_getCacheFile($key);
if($cacheFile" target="_blank">!@unlink($cacheFile)) {
throw new CacheException("Cache file could not be deleted");
}
return $this;
}
/**
* 缓存单元是否已经锁定
*
* @param string $key
* @return bool
*/
public function isLocked($key) {
$cacheFile = self::_getCacheFile($key);
clearstatcache();
return file_exists($cacheFile . ''.lock'');
}
/**
* 锁定
*
* @param string $key
* @return Cache_File
*/
public function lock($key) {
$cacheFile = self::_getCacheFile($key);
$cacheDir = dirname($cacheFile);
if(!is_dir($cacheDir)) {
if(mkdir($cacheDir" target="_blank">!@mkdir($cacheDir, 0755, true)) {
if(!is_dir($cacheDir)) {
throw new CacheException("Could not make cache directory");
}
}
}
// 设定缓存锁文件的访问和修改时间
@touch($cacheFile . ''.lock'');
return $this;
}
/**
* 解锁
*
* @param string $key
* @return Cache_File
*/
public function unlock($key) {
$cacheFile = self::_getCacheFile($key);
@unlink($cacheFile . ''.lock'');
return $this;
}
/**
* 设置文件缓存目录
* @param string $dir
* @return Cache_File
*/
protected function _setCacheDir($dir) {
$this->_cachesDir = rtrim(str_replace(''\\'', ''/'', trim($dir)), ''/'');
clearstatcache();
if(!is_dir($this->_cachesDir)) {
mkdir($this->_cachesDir, 0755, true);
}
//
retu