php实现数据缓存程序_PHP教程

WBOY
发布: 2016-07-13 17:07:20
原创
805 人浏览过

/**
 * 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;
  }
 }
}

?>

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/630437.htmlTechArticle?php /** * cache class */ class Cache { /** * cache path * * @var string */ var $cache_path; /** * timeout * * @var integer */ var $time = 60; /** * construct for this class * * @p...
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!