当前位置:首页 > PHP教程 > php高级应用 > 列表

php文件缓存类实例整理

发布:smiling 来源: PHP粉丝网  添加日期:2014-08-27 11:25:46 浏览: 评论:0 

缓存类是我们开发应用中会常用使用到的功能,下面我来给大家整理几个php文件缓存类了,各个文件缓存类写法不同,但在性能上会有区别,有兴趣测试的朋友可测试一下这些缓存类吧.

例1,代码如下:

  1. <?php 
  2. $fzz = new fzz_cache; 
  3. $fzz->kk = $_SERVER; //写入缓存 
  4. //$fzz->set("kk",$_SERVER,10000); //此方法不与类属性想冲突,可以用任意缓存名; 
  5. print_r($fzz->kk);  //读取缓存 
  6. //print_r($fzz->get("kk")); 
  7. //unset($fzz->kk); //删除缓存 
  8. //$fzz->_unset("kk"); 
  9. var_dump(isset($fzz->kk)); //判断缓存是否存在 
  10. //$fzz->_isset("kk"); 
  11. //$fzz->clear(); //清理过期缓存 
  12. //$fzz->clear_all(); //清理所有缓存文件 
  13. class fzz_cache{ 
  14.  public $limit_time = 20000; //缓存过期时间 
  15.  public $cache_dir = "data"; //缓存文件保存目录 
  16.  
  17.  //写入缓存 
  18.  function __set($key , $val){ 
  19.   $this->_set($key ,$val); 
  20.  } 
  21.  //第三个参数为过期时间 
  22.  function _set($key ,$val,$limit_time=null){   
  23.   $limit_time = $limit_time ? $limit_time : $this->limit_time; 
  24.   $file = $this->cache_dir."/".$key.".cache"; 
  25.   $val = serialize($val); 
  26.   @file_put_contents($file,$val) or $this->error(__line__,"fail to write in file"); 
  27.   @chmod($file,0777); 
  28.   @touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time"); 
  29.  } 
  30.  
  31.  
  32.  //读取缓存 
  33.  function __get($key){ 
  34.   return $this->_get($key); 
  35.  } 
  36.  function _get($key){ 
  37.   $file = $this->cache_dir."/".$key.".cache"; 
  38.   if (@filemtime($file)>=time()){ 
  39.    return unserialize(file_get_contents($file)); 
  40.   }else{ 
  41.    @unlink($file) or $this->error(__line__,"fail to unlink"); 
  42.    return false; 
  43.   } 
  44.  } 
  45.  
  46.  
  47.  //删除缓存文件 
  48.  function __unset($key){ 
  49.   return $this->_unset($key); 
  50.  } 
  51.  function _unset($key){ 
  52.   if (@unlink($this->cache_dir."/".$key.".cache")){ 
  53.    return true; 
  54.   }else{ 
  55.    return false; 
  56.   } 
  57.  } 
  58.  
  59.  
  60.  //检查缓存是否存在,过期则认为不存在 
  61.  function __isset($key){ 
  62.   return $this->_isset($key); 
  63.  } 
  64.  function _isset($key){ 
  65.   $file = $this->cache_dir."/".$key.".cache"; 
  66.   if (@filemtime($file)>=time()){ 
  67.    return true; 
  68.   }else{ 
  69.    @unlink($file) ; 
  70.    return false; 
  71.   } 
  72.  } 
  73.  
  74.  
  75.  //清除过期缓存文件 
  76.  function clear(){ 
  77.   $files = scandir($this->cache_dir); 
  78.   foreach ($files as $val){ 
  79.    if (filemtime($this->cache_dir."/".$val)<time()){ 
  80.     @unlink($this->cache_dir."/".$val); 
  81.    } 
  82.   } 
  83.  } 
  84.  
  85.  
  86.  //清除所有缓存文件 
  87.  function clear_all(){ 
  88.   $files = scandir($this->cache_dir); 
  89.   foreach ($files as $val){ 
  90.    @unlink($this->cache_dir."/".$val); 
  91.   } 
  92.  } 
  93.  
  94.  function error($msg,$debug = false) { 
  95.   $err = new Exception($msg); 
  96.   $str = "<pre> 
  97. <span style='color:red'>error:</span> 
  98. ".print_r($err->getTrace(),1)." 
  99. </pre>";//开源代码phpfensi.com 
  100.   if($debug == true) { 
  101.    file_put_contents(date('Y-m-d H_i_s').".log",$str); 
  102.    return $str; 
  103.   }else{ 
  104.    die($str); 
  105.   } 
  106.  } 
  107. } 
  108. ?> 

例2.从CI社区的stblog和CI的file_helper类中提取出来的php文件缓存类,一个简单的基于文件的key->value缓存类。

这个类可以用来缓存一些基本信息,比如博客的header,footer,sidebar中的一些不经常变化,从数据库中取出的内容,取数据前先判断文件缓存中的内容是否过期,如果没过期取出来,过期了则连接数据库查询,并将结果重新写入文件缓存,更新过期时间。跟memcache使用类似,不过更方便。用在一些小的应用上足够了...代码如下:

  1. <?php 
  2. define('DIRECTORY_SEPARATOR','/'); 
  3. define('FOPEN_WRITE_CREATE_DESTRUCTIVE','wb'); 
  4. define('FOPEN_WRITE_CREATE','ab'); 
  5. define('DIR_WRITE_MODE', 0777); 
  6. class FileCache { 
  7.  
  8.  /** 
  9.      * 缓存路径 
  10.      * 
  11.      * @access private 
  12.      * @var string 
  13.      */ 
  14.  private $_cache_path; 
  15.  
  16.  /** 
  17.      * 缓存过期时间,单位是秒second 
  18.      * 
  19.      * @access private 
  20.      * @var int 
  21.      */ 
  22.  private $_cache_expire; 
  23.  
  24.  /** 
  25.      * 解析函数,设置缓存过期实践和存储路径 
  26.      *  
  27.      * @access public 
  28.      * @return void 
  29.      */ 
  30.  public function __construct($expire, $cache_path) 
  31.  { 
  32.   $this->_cache_expire = $expire; 
  33.   $this->_cache_path = $cache_path; 
  34.  } 
  35.  
  36.  /** 
  37.      * 缓存文件名 
  38.      *  
  39.      * @access public 
  40.      * @param  string $key 
  41.      * @return void 
  42.      */ 
  43.  private function _file($key) 
  44.  { 
  45.   return $this->_cache_path . md5($key); 
  46.  } 
  47.  
  48.  /** 
  49.      * 设置缓存 
  50.      *  
  51.      * @access public 
  52.      * @param  string $key 缓存的唯一键 
  53.      * @param  string $data 缓存的内容 
  54.      * @return bool 
  55.      */ 
  56.  public function set($key, $data) 
  57.  { 
  58.   $value = serialize($data); 
  59.    
  60.   $file = $this->_file($key); 
  61.    
  62.      return $this->write_file($file, $value); 
  63.  } 
  64.  
  65.  /** 
  66.      * 获取缓存 
  67.      *  
  68.      * @access public 
  69.      * @param  string $key 缓存的唯一键 
  70.      * @return mixed 
  71.      */ 
  72.  public function get($key) 
  73.  { 
  74.   $file = $this->_file($key); 
  75.    
  76.   /** 文件不存在或目录不可写 */ 
  77.   if (!file_exists($file) || !$this->is_really_writable($file)) 
  78.   { 
  79.    return false; 
  80.   } 
  81.    
  82.   /** 缓存没有过期,仍然可用 */ 
  83.   if ( time() < (filemtime($file) + $this->_cache_expire) )  
  84.   { 
  85.     
  86.    $data = $this->read_file($file); 
  87.     
  88.    if(FALSE !== $data) 
  89.    { 
  90.     return unserialize($data); 
  91.    } 
  92.     
  93.    return FALSE; 
  94.   } 
  95.    
  96.   /** 缓存过期,删除之 */ 
  97.   @unlink($file); 
  98.   return FALSE; 
  99.   } 
  100.    
  101.   function read_file($file) 
  102.  { 
  103.   if ( ! file_exists($file)) 
  104.   { 
  105.    return FALSE; 
  106.   } 
  107.  
  108.   if (function_exists('file_get_contents')) 
  109.   { 
  110.    return file_get_contents($file);   
  111.   } 
  112.  
  113.   if ( ! $fp = @fopen($file, FOPEN_READ)) 
  114.   { 
  115.    return FALSE; 
  116.   } 
  117.    
  118.   flock($fp, LOCK_SH);//读取之前加上共享锁 
  119.  
  120.   $data = ''; 
  121.   if (filesize($file) > 0) 
  122.   { 
  123.    $data =& fread($fp, filesize($file)); 
  124.   } 
  125.  
  126.   flock($fp, LOCK_UN);//释放锁 
  127.   fclose($fp); 
  128.  
  129.   return $data; 
  130.  } 
  131.  
  132.   function write_file($path, $data, $mode = FOPEN_WRITE_CREATE_DESTRUCTIVE) 
  133.  { 
  134.   if ( ! $fp = @fopen($path, $mode)) 
  135.   { 
  136.    return FALSE; 
  137.   } 
  138.    
  139.   flock($fp, LOCK_EX); 
  140.   fwrite($fp, $data); 
  141.   flock($fp, LOCK_UN); 
  142.   fclose($fp);  
  143.  
  144.   return TRUE; 
  145.  } 
  146.  function is_really_writable($file)//兼容各平台判断文件是否有写入权限 
  147.  {  
  148.   // If we're on a Unix server with safe_mode off we call is_writable 
  149.   if (DIRECTORY_SEPARATOR == '/' AND @ini_get("safe_mode") == FALSE) 
  150.   { 
  151.    return is_writable($file); 
  152.   } 
  153.  
  154.   // For windows servers and safe_mode "on" installations we'll actually 
  155.   // write a file then read it.  Bah... 
  156.   if (is_dir($file)) 
  157.   { 
  158.    $file = rtrim($file, '/').'/'.md5(rand(1,100)); 
  159.  
  160.    if (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) 
  161.    { 
  162.     return FALSE; 
  163.    } 
  164.  
  165.    fclose($fp); 
  166.    @chmod($file, DIR_WRITE_MODE); 
  167.    @unlink($file); 
  168.    return TRUE; 
  169.   } 
  170.   elseif (($fp = @fopen($file, FOPEN_WRITE_CREATE)) === FALSE) 
  171.   {//开源代码phpfensi.com 
  172.    return FALSE; 
  173.   } 
  174.  
  175.   fclose($fp); 
  176.   return TRUE; 
  177.  } 
  178. } 
  179. $cache = new FileCache(30,'cache/'); 
  180. $cache->set('test','this is a test.'); 
  181. print $cache->get('test'); 
  182. /* End of file FlieCache.php */ 
  183. ?> 

例3.自己觉得很好用的php文件缓存,代码如下:

  1. <?php  
  2. class cache 
  3. {  
  4.  private static $_instance = null; 
  5.  
  6.     protected $_options = array( 
  7.         'cache_dir'        => "./", 
  8.         'file_name_prefix' => 'cache', 
  9.      'mode'            => '1', //mode 1 为serialize model 2为保存为可执行文件 
  10.     );  
  11.  
  12.  /** 
  13.   * 得到本类实例 
  14.   *  
  15.   * @return Ambiguous 
  16.   */ 
  17.  public static function getInstance() 
  18.  { 
  19.   if(self::$_instance === null) 
  20.   { 
  21.    self::$_instance = new self(); 
  22.   } 
  23.   return self::$_instance; 
  24.  }  
  25.  
  26.  /** 
  27.   * 得到缓存信息 
  28.   *  
  29.   * @param string $id 
  30.   * @return boolean|array 
  31.   */ 
  32.  public static function get($id) 
  33.  { 
  34.   $instance = self::getInstance(); 
  35.    
  36.   //缓存文件不存在 
  37.   if(!$instance->has($id)) 
  38.   { 
  39.    return false; 
  40.   } 
  41.    
  42.   $file = $instance->_file($id); 
  43.    
  44.   $data = $instance->_fileGetContents($file); 
  45.    
  46.   if($data['expire'] == 0 || time() < $data['expire']) 
  47.   { 
  48.    return $data['contents']; 
  49.   } 
  50.   return false; 
  51.  } 
  52.  
  53.  /** 
  54.   * 设置一个缓存 
  55.   *  
  56.   * @param string $id   缓存id 
  57.   * @param array  $data 缓存内容 
  58.   * @param int    $cacheLife 缓存生命 默认为0无限生命 
  59.   */ 
  60.  public static function set($id, $data, $cacheLife = 0) 
  61.  { 
  62.   $instance = self::getInstance(); 
  63.    
  64.   $time = time(); 
  65.   $cache      = array(); 
  66.   $cache['contents'] = $data; 
  67.   $cache['expire']   = $cacheLife === 0 ? 0 : $time + $cacheLife; 
  68.   $cache['mtime']    = $time; 
  69.    
  70.   $file = $instance->_file($id); 
  71.    
  72.   return $instance->_filePutContents($file, $cache); 
  73.  } 
  74.  
  75.     /** 
  76.      * 清除一条缓存 
  77.      *  
  78.      * @param string cache id   
  79.      * @return void 
  80.      */    
  81.  public static function delete($id) 
  82.  { 
  83.   $instance = self::getInstance(); 
  84.    
  85.   if(!$instance->has($id)) 
  86.   { 
  87.    return false; 
  88.   } 
  89.      $file = $instance->_file($id); 
  90.      //删除该缓存 
  91.      return unlink($file); 
  92.  } 
  93.  
  94.  /** 
  95.   * 判断缓存是否存在 
  96.   *  
  97.   * @param string $id cache_id 
  98.   * @return boolean true 缓存存在 false 缓存不存在 
  99.   */ 
  100.  public static function has($id) 
  101.  { 
  102.   $instance = self::getInstance(); 
  103.   $file     = $instance->_file($id); 
  104.    
  105.   if(!is_file($file)) 
  106.   { 
  107.    return false; 
  108.   } 
  109.   return true; 
  110.  } 
  111.  
  112.  /** 
  113.   * 通过缓存id得到缓存信息路径 
  114.   * @param string $id 
  115.   * @return string 缓存文件路径 
  116.   */ 
  117.  protected function _file($id) 
  118.  { 
  119.   $instance  = self::getInstance(); 
  120.   $fileNmae  = $instance->_idToFileName($id); 
  121.   return $instance->_options['cache_dir'] . $fileNmae; 
  122.  }  
  123.  
  124.  /** 
  125.   * 通过id得到缓存信息存储文件名 
  126.   *  
  127.   * @param  $id 
  128.   * @return string 缓存文件名 
  129.   */ 
  130.  protected function _idToFileName($id) 
  131.  { 
  132.   $instance  = self::getInstance(); 
  133.   $prefix    = $instance->_options['file_name_prefix']; 
  134.   return $prefix . '---' . $id; 
  135.  } 
  136.  
  137.  /** 
  138.   * 通过filename得到缓存id 
  139.   *  
  140.   * @param  $id 
  141.   * @return string 缓存id 
  142.   */ 
  143.  protected function _fileNameToId($fileName) 
  144.  { 
  145.   $instance  = self::getInstance(); 
  146.   $prefix    = $instance->_options['file_name_prefix']; 
  147.   return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName); 
  148.  } 
  149.  
  150.  /** 
  151.   * 把数据写入文件 
  152.   *  
  153.   * @param string $file 文件名称 
  154.   * @param array  $contents 数据内容 
  155.   * @return bool  
  156.   */ 
  157.  protected function _filePutContents($file, $contents) 
  158.  { 
  159.   if($this->_options['mode'] == 1) 
  160.   { 
  161.    $contents = serialize($contents); 
  162.   } 
  163.   else  
  164.   { 
  165.    $time = time();  
  166.          $contents = "<?phpn". 
  167.                  " // mktime: ". $time. "n". 
  168.                  " return ". 
  169.                  var_export($contents, true). 
  170.                  "n?>"; 
  171.   } 
  172.    
  173.   $result = false; 
  174.      $f = @fopen($file, 'w'); 
  175.         if ($f) { 
  176.             @flock($f, LOCK_EX); 
  177.             fseek($f, 0); 
  178.             ftruncate($f, 0); 
  179.             $tmp = @fwrite($f, $contents); 
  180.             if (!($tmp === false)) { 
  181.                 $result = true; 
  182.             } 
  183.             @fclose($f); 
  184.         } 
  185.   @chmod($file,0777); 
  186.   return $result;     
  187.  } 
  188.  
  189.  /** 
  190.   * 从文件得到数据 
  191.   *  
  192.   * @param  sring $file 
  193.   * @return boolean|array 
  194.   */ 
  195.  protected function _fileGetContents($file) 
  196.  { 
  197.   if(!is_file($file)) 
  198.   { 
  199.    return false; 
  200.   } 
  201.    
  202.   if($this->_options['mode'] == 1) 
  203.   { 
  204.    $f = @fopen($file, 'r');  
  205.    @$data = fread($f,filesize($file)); 
  206.    @fclose($f); 
  207.    return unserialize($data); 
  208.   } 
  209.   else 
  210.   { 
  211.    return include $file; 
  212.   } 
  213.  } 
  214.  
  215.  /** 
  216.   * 构造函数 
  217.   */ 
  218.  protected function __construct() 
  219.  { 
  220.  
  221.  } 
  222.  
  223.  /** 
  224.   * 设置缓存路径 
  225.   *  
  226.   * @param string $path 
  227.   * @return self 
  228.   */ 
  229.  public static function setCacheDir($path) 
  230.  { 
  231.   $instance  = self::getInstance(); 
  232.         if (!is_dir($path)) { 
  233.             exit('file_cache: ' . $path.' 不是一个有效路径 '); 
  234.         } 
  235.         if (!is_writable($path)) { 
  236.             exit('file_cache: 路径 "'.$path.'" 不可写'); 
  237.         } 
  238.      
  239.         $path = rtrim($path,'/') . '/'; 
  240.         $instance->_options['cache_dir'] = $path; 
  241.          
  242.         return $instance; 
  243.  } 
  244.  
  245.  /** 
  246.   * 设置缓存文件前缀 
  247.   *  
  248.   * @param srting $prefix 
  249.   * @return self 
  250.   */ 
  251.  public static function setCachePrefix($prefix) 
  252.  { 
  253.   $instance  = self::getInstance(); 
  254.   $instance->_options['file_name_prefix'] = $prefix; 
  255.   return $instance; 
  256.  } 
  257.  
  258.  /** 
  259.   * 设置缓存存储类型 
  260.   *  
  261.   * @param int $mode 
  262.   * @return self 
  263.   */ 
  264.  public static function setCacheMode($mode = 1) 
  265.  { 
  266.   $instance  = self::getInstance(); 
  267.   if($mode == 1) 
  268.   { 
  269.    $instance->_options['mode'] = 1; 
  270.   } 
  271.   else 
  272.   { 
  273.    $instance->_options['mode'] = 2; 
  274.   } 
  275.    
  276.   return $instance; 
  277.  } 
  278.  
  279.  /** 
  280.   * 删除所有缓存 
  281.   * @return boolean 
  282.   */ 
  283.  public static function flush() 
  284.  { 
  285.   $instance  = self::getInstance(); 
  286.   $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*'); 
  287.    
  288.   if(emptyempty($glob)) 
  289.   { 
  290.    return false; 
  291.   } 
  292.    
  293.   foreach ($glob as $v) 
  294.   { 
  295.    $fileName = basename($v); 
  296.    $id =  $instance->_fileNameToId($fileName); 
  297.    $instance->delete($id); 
  298.   } 
  299.   return true; 
  300.  } 
  301. } 
  302.  
  303. /* 初始化设置cache的配置信息什么的 */ 
  304. cache::setCachePrefix('core'); //设置缓存文件前缀 
  305. cache::setCacheDir('./cache'); //设置存放缓存文件夹路径 
  306.  
  307. //模式1 缓存存储方式 
  308. //a:3:{s:8:"contents";a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:34;i:4;i:5;i:5;i:6;i:6;i:6;}s:6:"expire";i:0;s:5:"mtime";i:1318218422;} 
  309. //模式2 缓存存储方式 
  310. /* 
  311.  <?php 
  312.  // mktime: 1318224645 
  313.  return array ( 
  314.   'contents' =>  
  315.   array ( 
  316.     0 => 1, 
  317.     1 => 2, 
  318.     2 => 3, 
  319.     3 => 34, 
  320.     4 => 5, 
  321.     5 => 6, 
  322.     6 => 6, 
  323.   ), 
  324.   'expire' => 0, 
  325.   'mtime' => 1318224645, 
  326. ) 
  327. ?> 
  328.  *  
  329.  *  
  330.  */ 
  331. cache::setCacheMode('2'); 
  332.  
  333. if(!$row = cache::get('zj2')) 
  334. { 
  335.  
  336.  $array = array(1,2,3,34,5,6,6); 
  337.  $row = cache::set('zj2',$array); 
  338. } 
  339. // cache::flush(); 清空所有缓存 
  340.  
  341. print_r($row); 
  342.  
  343. 件缓存 class     
  344.  
  345. <?php 
  346. /** 
  347.  * 文件缓存类 
  348.  * @author  xiaojiong & 290747680@qq.com 
  349.  * @date 2011-08-17 
  350.  */ 
  351. class cache 
  352. { 
  353.  const FILE_LIFE_KEY = 'FILE_LIFE_KEY'; 
  354.  
  355.  const CLEAR_ALL_KEY = 'CLEAR_ALL'; 
  356.  
  357.     static $_instance = null; 
  358.  
  359.     protected $_options = array( 
  360.         'cache_dir' => './cache', 
  361.         'file_locking' => true, 
  362.         'file_name_prefix' => 'cache', 
  363.         'cache_file_umask' => 0777, 
  364.      'file_life'  => 100000 
  365.     ); 
  366.      
  367.     static function &getInstance($options = array()) 
  368.     { 
  369.      if(self::$_instance === null) 
  370.      { 
  371.       self::$_instance = new self($options); 
  372.      }  
  373.      return self::$_instance; 
  374.     } 
  375.      
  376.     /** 
  377.      * 设置参数 
  378.      * @param  array $options 缓存参数 
  379.      * @return void 
  380.      */ 
  381.  static function &setOptions($options = array()) 
  382.  { 
  383.          return self::getInstance($options); 
  384.  } 
  385.  
  386.     /** 
  387.      * 构造函数 
  388.      * @param  array $options 缓存参数 
  389.      * @return void 
  390.      */ 
  391.     private function __construct($options = array()) 
  392.     {   
  393.         if ($this->_options['cache_dir'] !== null) { 
  394.     
  395.    $dir = rtrim($this->_options['cache_dir'],'/') . '/'; 
  396.          $this->_options['cache_dir'] = $dir; 
  397.           
  398.    if (!is_dir($this->_options['cache_dir'])) { 
  399.              mkdir($this->_options['cache_dir'],0777,TRUE); 
  400.          } 
  401.          if (!is_writable($this->_options['cache_dir'])) { 
  402.              exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写'); 
  403.          } 
  404.        
  405.         } else { 
  406.            exit('file_cache: "options" cache_dir 不能为空 '); 
  407.         } 
  408.     } 
  409.  
  410.     /** 
  411.      * 设置缓存路径 
  412.      * @param  string  $value 
  413.      * @return void 
  414.      */ 
  415.     static function setCacheDir($value) 
  416.     { 
  417.      $self = & self::getInstance(); 
  418.       
  419.         if (!is_dir($value)) { 
  420.             exit('file_cache: ' . $value.' 不是一个有效路径 '); 
  421.         } 
  422.         if (!is_writable($value)) { 
  423.             exit('file_cache: 路径 "'.$value.'" 不可写'); 
  424.         } 
  425.      
  426.         $value = rtrim($this->_options['cache_dir'],'/') . '/'; 
  427.          
  428.         $self->_options['cache_dir'] = $value; 
  429.     } 
  430.      
  431.     /** 
  432.      * 存入缓存数据 
  433.      * @param  array  $data          放入缓存的数据 
  434.      * @param  string $id            缓存id(又名缓存识别码) 
  435.      * @param  cache_life            缓存时间 
  436.      * @return boolean True if no problem 
  437.      */ 
  438.     static function save($data, $id = null, $cache_life = null) 
  439.     { 
  440.      $self = & self::getInstance(); 
  441.         if (!$id) { 
  442.             if ($self->_id) { 
  443.                 $id = $self->_id; 
  444.             } else { 
  445.                 exit('file_cache:save() id 不能为空!'); 
  446.             } 
  447.         } 
  448.         $time = time(); 
  449.          
  450.         if($cache_life) { 
  451.          $data[self::FILE_LIFE_KEY] = $time + $cache_life; 
  452.         } 
  453.   elseif 
  454.   ($cache_life != 0){ 
  455.          $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life']; 
  456.         } 
  457.          
  458.         $file = $self->_file($id); 
  459.          
  460.         $data = "<?phpn". 
  461.                 " // mktime: ". $time. "n". 
  462.                 " return ". 
  463.                 var_export($data, true). 
  464.                 "n?>" 
  465.                 ; 
  466.          
  467.         $res = $self->_filePutContents($file, $data); 
  468.         return $res; 
  469.     } 
  470.      
  471.      
  472.     /** 
  473.      * 得到缓存信息 
  474.      * 
  475.      * @param  string  $id  缓存id 
  476.      * @return string|array 缓存数据 
  477.      */ 
  478.     static function load($id) 
  479.     { 
  480.         $self = & self::getInstance(); 
  481.      $time = time(); 
  482.      //检测缓存是否存在 
  483.      if (!$self->test($id)) { 
  484.             // The cache is not hit ! 
  485.             return false; 
  486.         } 
  487.          
  488.   //全部清空识别文件 
  489.         $clearFile = $self->_file(self::CLEAR_ALL_KEY); 
  490.    
  491.   $file = $self->_file($id); 
  492.    
  493.         //判断缓存是否已被全部清除 
  494.      if(is_file($clearFile) && filemtime($clearFile) > filemtime($file)) 
  495.      { 
  496.       return false; 
  497.      } 
  498.         
  499.         $data = $self->_fileGetContents($file); 
  500.       if(emptyempty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) { 
  501.             unset($data[self::FILE_LIFE_KEY]);  
  502.        return $data;    
  503.       } 
  504.       return false; 
  505.     }     
  506.      
  507.     /** 
  508.      * 写入缓存文件 
  509.      * 
  510.      * @param  string $file   缓存路径 
  511.      * @param  string $string 缓存信息 
  512.      * @return boolean true 成功 
  513.      */ 
  514.     protected function _filePutContents($file, $string) 
  515.     { 
  516.      $self = & self::getInstance(); 
  517.         $result = false; 
  518.         $f = @fopen($file, 'ab+'); 
  519.         if ($f) { 
  520.             if ($self->_options['file_locking']) @flock($f, LOCK_EX); 
  521.             fseek($f, 0); 
  522.             ftruncate($f, 0); 
  523.             $tmp = @fwrite($f, $string); 
  524.             if (!($tmp === false)) { 
  525.                 $result = true; 
  526.             } 
  527.             @fclose($f); 
  528.         } 
  529.         @chmod($file, $self->_options['cache_file_umask']); 
  530.         return $result; 
  531.     } 
  532.      
  533.     /** 
  534.      * 格式化后的缓存文件路径 
  535.      * 
  536.      * @param  string $id 缓存id 
  537.      * @return string 缓存文件名(包括路径) 
  538.      */ 
  539.     protected function _file($id) 
  540.     { 
  541.      $self = & self::getInstance(); 
  542.         $fileName = $self->_idToFileName($id); 
  543.         return $self->_options['cache_dir'] . $fileName; 
  544.     }     
  545.      
  546.     /** 
  547.      * 格式化后的缓存文件名字 
  548.      * 
  549.      * @param  string $id 缓存id 
  550.      * @return string 缓存文件名 
  551.      */ 
  552.     protected function _idToFileName($id) 
  553.     { 
  554.      $self = & self::getInstance(); 
  555.         $self->_id = $id; 
  556.         $prefix = $self->_options['file_name_prefix']; 
  557.         $result = $prefix . '---' . $id; 
  558.         return $result; 
  559.     }    
  560.      
  561.     /** 
  562.      * 判断缓存是否存在 
  563.      * 
  564.      * @param  string $id Cache id 
  565.      * @return boolean True 缓存存在 False 缓存不存在 
  566.      */ 
  567.     static function test($id) 
  568.     { 
  569.      $self = & self::getInstance(); 
  570.         $file = $self->_file($id); 
  571.          
  572.         if (!is_file($file)) { 
  573.             return false; 
  574.         } 
  575.          
  576.         return true; 
  577.     } 
  578.      
  579.     /** 
  580.      * 得到缓存信息 
  581.      * 
  582.      * @param  string $file 缓存路径 
  583.      * @return string 缓存内容 
  584.      */ 
  585.     protected function _fileGetContents($file) 
  586.     { 
  587.         if (!is_file($file)) { 
  588.             return false; 
  589.         } 
  590.         return include $file; 
  591.     }      
  592.      
  593.     /** 
  594.      * 清除所有缓存 
  595.      *  
  596.      * @return void 
  597.      */     
  598.     static function clear() 
  599.     { 
  600.      $self = & self::getInstance(); 
  601.      $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY);  
  602.     }    
  603.  
  604.     /** 
  605.      * 清除一条缓存 
  606.      *  
  607.      * @param string cache id   
  608.      * @return void 
  609.      */    
  610.     static function del($id) 
  611.     { 
  612.   $self = & self::getInstance(); 
  613.      if(!$self->test($id)){ 
  614.       // 该缓存不存在 
  615.       return false; 
  616.      } 
  617.      $file = $self->_file($id); 
  618.      return unlink($file); 
  619.     }  
  620. } 
  621.  
  622. 存入数据 
  623.  
  624. <?php 
  625. $config = array( 
  626.  'name' => 'xiaojiong', 
  627.  'qq'   => '290747680', 
  628.  'age'  => '20', 
  629. ); 
  630.  
  631. //第一个参数 缓存data 
  632. //第二个参数 缓存id 
  633. //第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life 
  634. cache::save($config,'config',0); 
  635.  
  636. 载入数据 
  637.  
  638. <?php 
  639. //只有一个参数 cache_id 
  640. $config = cache::load('config'); 
  641.  
  642. 清空缓存 
  643.  
  644. <?php 
  645. //清空指定缓存 
  646. cache::del('config'); 
  647. //清空所有缓存 
  648. cache::clear(); 
  649.  
  650. cache信息配置 
  651.  
  652. //在执行所有cache_func前调用 
  653.  
  654. $_options = array( 
  655.     'cache_dir' => './cache', //缓存文件目录 
  656.     'file_name_prefix' => 'cache',//缓存文件前缀 
  657.     'file_life'  => 100000, //缓存文件生命 
  658. ); 
  659. cache::setOptions($options); 
  660.  
  661. //再执行 就会按着新配置信息执行,否则是默认信息 
  662. cache::save($arr,'arr'); 
  663.  
  664. //就是这个方法 貌似不合理 望大家指点 
  665. ?> 

Tags: php文件缓存 php缓存类

分享到: