php实现数据缓存程序_PHP教程
* cache class
*/
class Cache {
/**
* cache path
*
* @var string
*/
var $cache_path;
/**
* timeout
*
* @var integer
*/
var $time = 60;
/**
* construct for this class
*
* @param string $cache_path
* @return Cache
*/
function Cache($cache_path = 'cache') {
if(is_dir($cache_path)) {
$this->cache_path = rtrim($cache_path,'/').'/';
} else {
die('cache dir is not exists.');
}
}
/**
* set timeout
*
* @param integer $time
* @return boolean
*/
function setTime($time) {
if(isset($time) && is_integer($time)) {
$this->time = $time;
return true;
} else {
return false;
}
}
/**
* read cache
*
* @param string $cache_id
* @return mixed
*/
function read($cache_id) {
$cache_file = $this->cache_path.$cache_id.'.cache';
if(!file_exists($cache_file)) {
return false;
}
$mtime = filemtime($cache_file);
if((time() - $mtime) > $this->time) {
return false;
} else {
$fp = fopen($cache_file,'r');
$content = fread($fp,filesize($cache_file));
fclose($fp);
unset($fp);
if($content) {
return unserialize($content);
} else {
return false;
}
}
}
/**
* write cache in a file
*
* @param string $content
* @param string $cache_id
* @return boolean
*/
function write($content,$cache_id) {
$cache_file = $this->cache_path.$cache_id.'.cache';
if(file_exists($cache_file)) {
@unlink($cache_file);
}
$fp = fopen($cache_file,'w');
$content = serialize($content);
if(fwrite($fp,$content)) {
fclose($fp);
unset($fp);
return true;
} else {
fclose($fp);
unset($fp);
return false;
}
}
/**
* clean all cache
*
* @param string $path
* @return boolean
*/
function cleanCache($path = 'cache') {
if(is_dir($path)) {
$path = rtrim($path,'/').'/';
$handler = opendir($path);
while (($f = readdir($handler)) !== false) {
if(!is_dir($f)) {
if($f != '.' && $f != '..') {
@unlink($path.$f);
}
} else {
$this->cleanCache($f);
}
}
} else {
return false;
}
}
}
?>
推荐阅读
-
正确理解PHP程序编译时的错误信息_PHP教程
-
php利用func_get_arg,func_get_args,func_num_args实现伪重载_PHP教程
-
Bo-Blog专用的给Windows服务器的IIS Rewrite程序_PHP教程
-
PHP程序与服务器端通讯的方法_PHP教程
-
使用APC缓存PHP_PHP教程
-
实现php加速的eAccelerator dll支持文件打包下载_PHP教程
-
php导入大量数据到mysql性能优化技巧,mysql性能优化_PHP教程
-
PHP排序之二维数组的按照字母排序实现代码_PHP教程
-
php基于session实现数据库交互的类实例_PHP
-
php读取excel日期类型数据的例子_PHP教程