PHP:[Copy to clipboard] <?php class cache{ /* Class Name: cache Description: control to cache data,$cache_out_time is a array to save cache date time out. Version: 1.0 Author: 老农 cjjer Last modify:2006-2-26 Author URL: http://www.cjjer.com */ private $cache_dir; private $expireTime=180;//缓存的时间是 60 秒 function __construct($cache_dirname){ if(!@is_dir($cache_dirname)){ if(!@mkdir($cache_dirname,0777)){ $this->warn('缓存文件不存在而且不能创建,需要手动创建.'); return false; } } $this->cache_dir = $cache_dirname; } function __destruct(){ echo 'Cache class bye.'; }
function readData($cacheFile='default_cache.txt'){ $cacheFile = $this->cache_dir."/".$cacheFile; if(file_exists($cacheFile)&&filemtime($cacheFile)>(time()-$this->expireTime)){ $data=$this->display_cache($cacheFile); }else{ $data="from here wo can get it from mysql database,update time is <b>".date('l dS of F Y h:i:s A')."</b>,过期时间是:".date('l dS of F Y h:i:s A',time()+$this->expireTime)."----------"; $this->cache_page($cacheFile,$data); } return $data; }
} ?>
下面我打断这个代码逐行解释.
三、程序透析
这个缓存类(类没什么好怕的.请继续看)名称是cache,有2个属性:
CODE:[Copy to clipboard]private $cache_dir; private $expireTime=180; $cache_dir是缓存文件所放的相对网站目录的父目录, $expireTime(注释一)是我们缓存的数据过期的时间,主要是这个思路: 当数据或者文件被加载的时候,先判断缓存文件存在不,返回false ,文件最后修改时间和缓存的时间和比当前时间大不,大的话说明缓存还没到期,小的话返回false,当返回false的时候,读取原始数据,写入缓存文件中,返回数据.
接着看程序:
PHP:[Copy to clipboard] function __construct($cache_dirname){ if(!@is_dir($cache_dirname)){ if(!@mkdir($cache_dirname,0777)){ $this->warn('缓存文件不存在而且不能创建,需要手动创建.'); return false; } } $this->cache_dir = $cache_dirname; }
function readData($cacheFile='default_cache.txt'){ $cacheFile = $this->cache_dir."/".$cacheFile; if(file_exists($cacheFile)&&filemtime($cacheFile)>(time()-$this->expireTime)){ $data=$this->display_cache($cacheFile); }else{ $data="from here wo can get it from mysql database,update time is <b>".date('l dS of F Y h:i:s A')."</b>,过期时间是:".date('l dS of F Y h:i:s A',time()+$this->expireTime)."----------"; $this->cache_page($cacheFile,$data); } return $data; }