分类目录

链接

2012 年 11 月
 1234
567891011
12131415161718
19202122232425
2627282930  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > PHP > 正文
PHP缓存类
PHP 暂无评论 阅读(1,668)
  1. //PHP缓存类
  2. <?php
  3. class Cache {
  4.     private $cache_path;//path for the cache
  5.     private $cache_expire;//seconds that the cache expires
  6.  
  7.     //cache constructor, optional expiring time and cache path
  8.     public function Cache($exp_time=3600,$path="cache/"){
  9.         $this->cache_expire=$exp_time;
  10.         $this->cache_path=$path;
  11.     }
  12.  
  13.     //returns the filename for the cache
  14.     private function fileName($key){
  15.         return $this->cache_path.md5($key);
  16.     }
  17.  
  18.     //creates new cache files with the given data, $key== name of the cache, data the info/values to store
  19.     public function put($key, $data){
  20.         $values = serialize($data);
  21.         $filename = $this->fileName($key);
  22.         $file = fopen($filename, 'w');
  23.         if ($file){//able to create the file
  24.             fwrite($file, $values);
  25.             fclose($file);
  26.         }
  27.         else return false;
  28.     }
  29.  
  30.     //returns cache for the given key
  31.     public function get($key){
  32.         $filename = $this->fileName($key);
  33.         if (!file_exists($filename) || !is_readable($filename)){//can't read the cache
  34.             return false;
  35.         }
  36.         if ( time() < (filemtime($filename) + $this->cache_expire) ) {//cache for the key not expired
  37.             $file = fopen($filename, "r");// read data file
  38.             if ($file){//able to open the file
  39.                 $data = fread($file, filesize($filename));
  40.                 fclose($file);
  41.                 return unserialize($data);//return the values
  42.             }
  43.             else return false;
  44.         }
  45.         else return false;//was expired you need to create new
  46.      }
  47. }
  48. ?>

 

  1. 使用说明:
  2.  
  3. 1、实例化
  4.  
  5. $cache = new Cache();
  6.  
  7. 2、设置缓存时间和缓存目录
  8.  
  9. $cache = new Cache(60, '/any_other_path/');
  10.  
  11. 第一个参数是缓存秒数,第二个参数是缓存路径,根据需要配置。
  12. 默认情况下,缓存时间是 3600 秒,缓存目录是 cache/
  13.  
  14. 3、读取缓存
  15.  
  16. $value = $cache->get('data_key');
  17.  
  18. 4、写入缓存
  19.  
  20. $value = $cache->put('data_key', 'data_value');
  21.  
  22. 完整实例:
  23.  
  24. $cache = new Cache();
  25.  
  26. //从缓存从读取键值 $key 的数据
  27. $values = $cache->get($key);
  28.  
  29. //如果没有缓存数据
  30. if ($values == false) {
  31.     //insert code here...
  32.     //写入键值 $key 的数据
  33.     $cache->put($key, $values);
  34. } else {
  35.     //insert code here...
  36. }

 

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:PHP缓存类 | Bruce's Blog

发表评论

留言无头像?