PHP的数据级缓存


 

PHP代码
  1. <?php   
  2. /**  
  3.  * 数据级缓存类  
  4.  */  
  5. !defined('IN_TEA') && exit('Access Denied');   
  6.   
  7. class dataCache {   
  8.     public $fileName;   
  9.     public $cacheTime;   
  10.     function __construct(){   
  11.            
  12.     }   
  13.     function C($cacheName,$cacheValue = false,$cacheTime = 0){   
  14.         $this->fileName = TEA_CACHE_DIR.'dataCache/'.md5($cacheName);   
  15.         if($cacheValue===false){   
  16.             #  读取缓存   
  17.             if (!file_exists($this->fileName))   
  18.                 return false;   
  19.             $data = tReadFile($this->fileName);   
  20.             $this->cacheTime = intval(substr($data,0,5));   
  21.             if ($this->isActive())   
  22.                 return unserialize(substr($data,5));   
  23.             else    
  24.                 return false;   
  25.         }   
  26.         else  
  27.         {   
  28.             #写入缓存   
  29.             tWriteFile($this->fileName,sprintf("%05d"$cacheTime).serialize($cacheValue),'w+');   
  30.         }   
  31.     }   
  32.     /**  
  33.      * 检测缓存是否过期  
  34.      *  
  35.      * @return bool true/false  
  36.      */  
  37.     private function isActive(){   
  38.         if ($this->cacheTime==0)   
  39.             return true;   
  40.         else if(0<(time() - (filemtime($this->fileName)+$this->cacheTime))) {   
  41.             #缓存过期   
  42.             return false;   
  43.         }   
  44.         else  
  45.             return true;   
  46.     }   
  47.     /**  
  48.      * 清理缓存  
  49.      *  
  50.      */  
  51.     public function clearCache(){   
  52.         $directory = dir(TEA_CACHE_DIR.'dataCache/');   
  53.         while($entry = $directory->read()) {   
  54.             $filename = $dir.'/'.$entry;   
  55.             if(is_file($filename)) {   
  56.                 @unlink($filename);    
  57.             }   
  58.         }    
  59.         $directory->close();   
  60.     }   
  61.   
  62. }   
  63.   
  64. ?>   

Tags: php, 缓存

« 上一篇 | 下一篇 »

shiny

拜读了半年前自己的类,感觉现在的自己进步不少

心中暗爽

Post on 2009, August 13, 2:14 AM 1


Comment (require):