VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > PHP >
  • php文件缓存类汇总

这篇文章主要介绍了php文件缓存类,实例汇总了常见的文件缓存类及其用法,非常具有实用价值,需要的朋友可以参考下

本文实例讲述了php的文件缓存类。分享给大家供大家参考。具体分析如下:

缓存类是我们开发应用中会常用使用到的功能,下面就来给大家整理几个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.  function __set($key , $val){ 
  18.   $this->_set($key ,$val); 
  19.  } 
  20.  //第三个参数为过期时间 
  21.  function _set($key ,$val,$limit_time=null){  
  22.   $limit_time = $limit_time ? $limit_time : $this->limit_time; 
  23.   $file = $this->cache_dir."/".$key.".cache"; 
  24.   $val = serialize($val); 
  25.   @file_put_contents($file,$val) or $this->error(__line__,"fail to write in file"); 
  26.   @chmod($file,0777); 
  27.   @touch($file,time()+$limit_time) or $this->error(__line__,"fail to change time"); 
  28.  } 
  29.  //读取缓存 
  30.  function __get($key){ 
  31.   return $this->_get($key); 
  32.  } 
  33.  function _get($key){ 
  34.   $file = $this->cache_dir."/".$key.".cache"; 
  35.   if (@filemtime($file)>=time()){ 
  36.    return unserialize(file_get_contents($file)); 
  37.   }else{ 
  38.    @unlink($file) or $this->error(__line__,"fail to unlink"); 
  39.    return false; 
  40.   } 
  41.  } 
  42.  
  43.  //删除缓存文件 
  44.  function __unset($key){ 
  45.   return $this->_unset($key); 
  46.  } 
  47.  function _unset($key){ 
  48.   if (@unlink($this->cache_dir."/".$key.".cache")){ 
  49.    return true; 
  50.   }else{ 
  51.    return false; 
  52.   } 
  53.  } 
  54.  
  55.  //检查缓存是否存在,过期则认为不存在 
  56.  function __isset($key){ 
  57.   return $this->_isset($key); 
  58.  } 
  59.  function _isset($key){ 
  60.   $file = $this->cache_dir."/".$key.".cache"; 
  61.   if (@filemtime($file)>=time()){ 
  62.    return true; 
  63.   }else{ 
  64.    @unlink($file) ; 
  65.    return false; 
  66.   } 
  67.  } 
  68.  
  69.  //清除过期缓存文件 
  70.  function clear(){ 
  71.   $files = scandir($this->cache_dir); 
  72.   foreach ($files as $val){ 
  73.    if (filemtime($this->cache_dir."/".$val)<time()){ 
  74.     @unlink($this->cache_dir."/".$val); 
  75.    } 
  76.   } 
  77.  } 
  78.  
  79.  //清除所有缓存文件 
  80.  function clear_all(){ 
  81.   $files = scandir($this->cache_dir); 
  82.   foreach ($files as $val){ 
  83.    @unlink($this->cache_dir."/".$val); 
  84.   } 
  85.  } 
  86.  
  87.  function error($msg,$debug = false) { 
  88.   $err = new Exception($msg); 
  89.   $str = "<pre> 
  90. <span style='color:red'>error:</span> 
  91. ".print_r($err->getTrace(),1)." 
  92. </pre>"; 
  93.   if($debug == true) { 
  94.    file_put_contents(date('Y-m-d H_i_s').".log",$str); 
  95.    return $str; 
  96.   }else{ 
  97.    die($str); 
  98.   } 
  99.  } 
  100. } 
  101. ?> 

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

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

  1. <?php 
  2. class cache 
  3. { 
  4.  private static $_instance = null; 
  5.     protected $_options = array( 
  6.         'cache_dir'        => "./", 
  7.         'file_name_prefix' => 'cache', 
  8.      'mode'            => '1', //mode 1 为serialize model 2为保存为可执行文件 
  9.     ); 
  10.  
  11.  /** 
  12.   * 得到本类实例 
  13.   * 
  14.   * @return Ambiguous 
  15.   */ 
  16.  public static function getInstance() 
  17.  { 
  18.   if(self::$_instance === null) 
  19.   { 
  20.    self::$_instance = new self(); 
  21.   } 
  22.   return self::$_instance; 
  23.  } 
  24.  
  25.  /** 
  26.   * 得到缓存信息 
  27.   * 
  28.   * @param string $id 
  29.   * @return boolean|array 
  30.   */ 
  31.  public static function get($id) 
  32.  { 
  33.   $instance = self::getInstance(); 
  34.  
  35.   //缓存文件不存在 
  36.   if(!$instance->has($id)) 
  37.   { 
  38.    return false; 
  39.   } 
  40.  
  41.   $file = $instance->_file($id); 
  42.  
  43.   $data = $instance->_fileGetContents($file); 
  44.  
  45.   if($data['expire'] == 0 || time() < $data['expire']) 
  46.   { 
  47.    return $data['contents']; 
  48.   } 
  49.   return false; 
  50.  } 
  51.  
  52.  /** 
  53.   * 设置一个缓存 
  54.   * 
  55.   * @param string $id   缓存id 
  56.   * @param array  $data 缓存内容 
  57.   * @param int    $cacheLife 缓存生命 默认为0无限生命 
  58.   */ 
  59.  public static function set($id, $data, $cacheLife = 0) 
  60.  { 
  61.   $instance = self::getInstance(); 
  62.  
  63.   $time = time(); 
  64.   $cache      = array(); 
  65.   $cache['contents'] = $data; 
  66.   $cache['expire']   = $cacheLife === 0 ? 0 : $time + $cacheLife; 
  67.   $cache['mtime']    = $time; 
  68.  
  69.   $file = $instance->_file($id); 
  70.  
  71.   return $instance->_filePutContents($file, $cache); 
  72.  } 
  73.  
  74.     /** 
  75.      * 清除一条缓存 
  76.      * 
  77.      * @param string cache id  
  78.      * @return void 
  79.      */   
  80.  public static function delete($id) 
  81.  { 
  82.   $instance = self::getInstance(); 
  83.  
  84.   if(!$instance->has($id)) 
  85.   { 
  86.    return false; 
  87.   } 
  88.      $file = $instance->_file($id); 
  89.      //删除该缓存 
  90.      return unlink($file); 
  91.  } 
  92.  
  93.  /** 
  94.   * 判断缓存是否存在 
  95.   * 
  96.   * @param string $id cache_id 
  97.   * @return boolean true 缓存存在 false 缓存不存在 
  98.   */ 
  99.  public static function has($id) 
  100.  { 
  101.   $instance = self::getInstance(); 
  102.   $file     = $instance->_file($id); 
  103.  
  104.   if(!is_file($file)) 
  105.   { 
  106.    return false; 
  107.   } 
  108.   return true; 
  109.  } 
  110.  
  111.  /** 
  112.   * 通过缓存id得到缓存信息路径 
  113.   * @param string $id 
  114.   * @return string 缓存文件路径 
  115.   */ 
  116.  protected function _file($id) 
  117.  { 
  118.   $instance  = self::getInstance(); 
  119.   $fileNmae  = $instance->_idToFileName($id); 
  120.   return $instance->_options['cache_dir'] . $fileNmae; 
  121.  } 
  122.  
  123.  /** 
  124.   * 通过id得到缓存信息存储文件名 
  125.   * 
  126.   * @param  $id 
  127.   * @return string 缓存文件名 
  128.   */ 
  129.  protected function _idToFileName($id) 
  130.  { 
  131.   $instance  = self::getInstance(); 
  132.   $prefix    = $instance->_options['file_name_prefix']; 
  133.   return $prefix . '---' . $id; 
  134.  } 
  135.  
  136.  /** 
  137.   * 通过filename得到缓存id 
  138.   * 
  139.   * @param  $id 
  140.   * @return string 缓存id 
  141.   */ 
  142.  protected function _fileNameToId($fileName) 
  143.  { 
  144.   $instance  = self::getInstance(); 
  145.   $prefix    = $instance->_options['file_name_prefix']; 
  146.   return preg_replace('/^' . $prefix . '---(.*)$/', '$1', $fileName); 
  147.  } 
  148.  
  149.  /** 
  150.   * 把数据写入文件 
  151.   * 
  152.   * @param string $file 文件名称 
  153.   * @param array  $contents 数据内容 
  154.   * @return bool 
  155.   */ 
  156.  protected function _filePutContents($file, $contents) 
  157.  { 
  158.   if($this->_options['mode'] == 1) 
  159.   { 
  160.    $contents = serialize($contents); 
  161.   } 
  162.   else 
  163.   { 
  164.    $time = time(); 
  165.          $contents = "<?phpn". 
  166.                  " // mktime: ". $time. "n". 
  167.                  " return ". 
  168.                  var_export($contents, true). 
  169.                  "n?>"; 
  170.   } 
  171.  
  172.   $result = false; 
  173.      $f = @fopen($file, 'w'); 
  174.         if ($f) { 
  175.             @flock($f, LOCK_EX); 
  176.             fseek($f, 0); 
  177.             ftruncate($f, 0); 
  178.             $tmp = @fwrite($f, $contents); 
  179.             if (!($tmp === false)) { 
  180.                 $result = true; 
  181.             } 
  182.             @fclose($f); 
  183.         } 
  184.   @chmod($file,0777); 
  185.   return $result;    
  186.  } 
  187.  
  188.  /** 
  189.   * 从文件得到数据 
  190.   * 
  191.   * @param  sring $file 
  192.   * @return boolean|array 
  193.   */ 
  194.  protected function _fileGetContents($file) 
  195.  { 
  196.   if(!is_file($file)) 
  197.   { 
  198.    return false; 
  199.   } 
  200.  
  201.   if($this->_options['mode'] == 1) 
  202.   { 
  203.    $f = @fopen($file, 'r'); 
  204.    @$data = fread($f,filesize($file)); 
  205.    @fclose($f); 
  206.    return unserialize($data); 
  207.   } 
  208.   else 
  209.   { 
  210.    return include $file; 
  211.   } 
  212.  } 
  213.  
  214.  /** 
  215.   * 构造函数 
  216.   */ 
  217.  protected function __construct() 
  218.  { 
  219.  
  220.  } 
  221.  
  222.  /** 
  223.   * 设置缓存路径 
  224.   * 
  225.   * @param string $path 
  226.   * @return self 
  227.   */ 
  228.  public static function setCacheDir($path) 
  229.  { 
  230.   $instance  = self::getInstance(); 
  231.         if (!is_dir($path)) { 
  232.             exit('file_cache: ' . $path.' 不是一个有效路径 '); 
  233.         } 
  234.         if (!is_writable($path)) { 
  235.             exit('file_cache: 路径 "'.$path.'" 不可写'); 
  236.         } 
  237.     
  238.         $path = rtrim($path,'/') . '/'; 
  239.         $instance->_options['cache_dir'] = $path; 
  240.         
  241.         return $instance; 
  242.  } 
  243.  
  244.  /** 
  245.   * 设置缓存文件前缀 
  246.   * 
  247.   * @param srting $prefix 
  248.   * @return self 
  249.   */ 
  250.  public static function setCachePrefix($prefix) 
  251.  { 
  252.   $instance  = self::getInstance(); 
  253.   $instance->_options['file_name_prefix'] = $prefix; 
  254.   return $instance; 
  255.  } 
  256.  
  257.  /** 
  258.   * 设置缓存存储类型 
  259.   * 
  260.   * @param int $mode 
  261.   * @return self 
  262.   */ 
  263.  public static function setCacheMode($mode = 1) 
  264.  { 
  265.   $instance  = self::getInstance(); 
  266.   if($mode == 1) 
  267.   { 
  268.    $instance->_options['mode'] = 1; 
  269.   } 
  270.   else 
  271.   { 
  272.    $instance->_options['mode'] = 2; 
  273.   } 
  274.  
  275.   return $instance; 
  276.  } 
  277.  
  278.  /** 
  279.   * 删除所有缓存 
  280.   * @return boolean 
  281.   */ 
  282.  public static function flush() 
  283.  { 
  284.   $instance  = self::getInstance(); 
  285.   $glob = @glob($instance->_options['cache_dir'] . $instance->_options['file_name_prefix'] . '--*'); 
  286.  
  287.   if(emptyempty($glob)) 
  288.   { 
  289.    return false; 
  290.   } 
  291.  
  292.   foreach ($glob as $v) 
  293.   { 
  294.    $fileName = basename($v); 
  295.    $id =  $instance->_fileNameToId($fileName); 
  296.    $instance->delete($id); 
  297.   } 
  298.   return true; 
  299.  } 
  300. } 
  301. /* 初始化设置cache的配置信息什么的 */ 
  302. cache::setCachePrefix('core'); //设置缓存文件前缀 
  303. cache::setCacheDir('./cache'); //设置存放缓存文件夹路径 
  304. //模式1 缓存存储方式 
  305. //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;} 
  306. //模式2 缓存存储方式 
  307. /* 
  308.  <?php 
  309.  // mktime: 1318224645 
  310.  return array ( 
  311.   'contents' => 
  312.   array ( 
  313.     0 => 1, 
  314.     1 => 2, 
  315.     2 => 3, 
  316.     3 => 34, 
  317.     4 => 5, 
  318.     5 => 6, 
  319.     6 => 6, 
  320.   ), 
  321.   'expire' => 0, 
  322.   'mtime' => 1318224645, 
  323. ) 
  324. ?> 
  325.  * 
  326.  * 
  327.  */ 
  328. cache::setCacheMode('2'); 
  329. if(!$row = cache::get('zj2')) 
  330. { 
  331.  
  332.  $array = array(1,2,3,34,5,6,6); 
  333.  $row = cache::set('zj2',$array); 
  334. } 
  335. // cache::flush(); 清空所有缓存 
  336. print_r($row); 

文件缓存 class,代码如下:

  1. <?php 
  2. /** 
  3.  * 文件缓存类 
  4.  * @date 2011-08-17 
  5.  */ 
  6. class cache 
  7. { 
  8.  const FILE_LIFE_KEY = 'FILE_LIFE_KEY'; 
  9.  
  10.  const CLEAR_ALL_KEY = 'CLEAR_ALL'; 
  11.  
  12.     static $_instance = null; 
  13.  
  14.     protected $_options = array( 
  15.         'cache_dir' => './cache', 
  16.         'file_locking' => true, 
  17.         'file_name_prefix' => 'cache', 
  18.         'cache_file_umask' => 0777, 
  19.      'file_life'  => 100000 
  20.     ); 
  21.     
  22.     static function &getInstance($options = array()) 
  23.     { 
  24.      if(self::$_instance === null) 
  25.      { 
  26.       self::$_instance = new self($options); 
  27.      } 
  28.      return self::$_instance; 
  29.     } 
  30.     
  31.     /** 
  32.      * 设置参数 
  33.      * @param  array $options 缓存参数 
  34.      * @return void 
  35.      */ 
  36.  static function &setOptions($options = array()) 
  37.  { 
  38.          return self::getInstance($options); 
  39.  } 
  40.  
  41.     /** 
  42.      * 构造函数 
  43.      * @param  array $options 缓存参数 
  44.      * @return void 
  45.      */ 
  46.     private function __construct($options = array()) 
  47.     {  
  48.         if ($this->_options['cache_dir'] !== null) { 
  49.    
  50.    $dir = rtrim($this->_options['cache_dir'],'/') . '/'; 
  51.          $this->_options['cache_dir'] = $dir; 
  52.          
  53.    if (!is_dir($this->_options['cache_dir'])) { 
  54.              mkdir($this->_options['cache_dir'],0777,TRUE); 
  55.          } 
  56.          if (!is_writable($this->_options['cache_dir'])) { 
  57.              exit('file_cache: 路径 "'. $this->_options['cache_dir'] .'" 不可写'); 
  58.          } 
  59.       
  60.         } else { 
  61.            exit('file_cache: "options" cache_dir 不能为空 '); 
  62.         } 
  63.     } 
  64.     /** 
  65.      * 设置缓存路径 
  66.      * @param  string  $value 
  67.      * @return void 
  68.      */ 
  69.     static function setCacheDir($value) 
  70.     { 
  71.      $self = & self::getInstance(); 
  72.      
  73.         if (!is_dir($value)) { 
  74.             exit('file_cache: ' . $value.' 不是一个有效路径 '); 
  75.         } 
  76.         if (!is_writable($value)) { 
  77.             exit('file_cache: 路径 "'.$value.'" 不可写'); 
  78.         } 
  79.     
  80.         $value = rtrim($this->_options['cache_dir'],'/') . '/'; 
  81.         
  82.         $self->_options['cache_dir'] = $value; 
  83.     } 
  84.     
  85.     /** 
  86.      * 存入缓存数据 
  87.      * @param  array  $data          放入缓存的数据 
  88.      * @param  string $id            缓存id(又名缓存识别码) 
  89.      * @param  cache_life            缓存时间 
  90.      * @return boolean True if no problem 
  91.      */ 
  92.     static function save($data, $id = null, $cache_life = null) 
  93.     { 
  94.      $self = & self::getInstance(); 
  95.         if (!$id) { 
  96.             if ($self->_id) { 
  97.                 $id = $self->_id; 
  98.             } else { 
  99.                 exit('file_cache:save() id 不能为空!'); 
  100.             } 
  101.         } 
  102.         $time = time(); 
  103.         
  104.         if($cache_life) { 
  105.          $data[self::FILE_LIFE_KEY] = $time + $cache_life; 
  106.         } 
  107.   elseif 
  108.   ($cache_life != 0){ 
  109.          $data[self::FILE_LIFE_KEY] = $time + $self->_options['file_life']; 
  110.         } 
  111.         
  112.         $file = $self->_file($id); 
  113.         
  114.         $data = "<?phpn". 
  115.                 " // mktime: ". $time. "n". 
  116.                 " return ". 
  117.                 var_export($data, true). 
  118.                 "n?>" 
  119.                 ; 
  120.         
  121.         $res = $self->_filePutContents($file, $data); 
  122.         return $res; 
  123.     } 
  124.     
  125.     
  126.     /** 
  127.      * 得到缓存信息 
  128.      * 
  129.      * @param  string  $id  缓存id 
  130.      * @return string|array 缓存数据 
  131.      */ 
  132.     static function load($id) 
  133.     { 
  134.         $self = & self::getInstance(); 
  135.      $time = time(); 
  136.      //检测缓存是否存在 
  137.      if (!$self->test($id)) { 
  138.             // The cache is not hit ! 
  139.             return false; 
  140.         } 
  141.         
  142.   //全部清空识别文件 
  143.         $clearFile = $self->_file(self::CLEAR_ALL_KEY); 
  144.  
  145.   $file = $self->_file($id); 
  146.  
  147.         //判断缓存是否已被全部清除 
  148.      if(is_file($clearFile) && filemtime($clearFile) > filemtime($file)) 
  149.      { 
  150.       return false; 
  151.      } 
  152.        
  153.         $data = $self->_fileGetContents($file); 
  154.       if(emptyempty($data[self::FILE_LIFE_KEY]) || $time < $data[self::FILE_LIFE_KEY]) { 
  155.             unset($data[self::FILE_LIFE_KEY]); 
  156.        return $data;   
  157.       } 
  158.       return false; 
  159.     }    
  160.     
  161.     /** 
  162.      * 写入缓存文件 
  163.      * 
  164.      * @param  string $file   缓存路径 
  165.      * @param  string $string 缓存信息 
  166.      * @return boolean true 成功 
  167.      */ 
  168.     protected function _filePutContents($file, $string) 
  169.     { 
  170.      $self = & self::getInstance(); 
  171.         $result = false; 
  172.         $f = @fopen($file, 'ab+'); 
  173.         if ($f) { 
  174.             if ($self->_options['file_locking']) @flock($f, LOCK_EX); 
  175.             fseek($f, 0); 
  176.             ftruncate($f, 0); 
  177.             $tmp = @fwrite($f, $string); 
  178.             if (!($tmp === false)) { 
  179.                 $result = true; 
  180.             } 
  181.             @fclose($f); 
  182.         } 
  183.         @chmod($file, $self->_options['cache_file_umask']); 
  184.         return $result; 
  185.     } 
  186.     
  187.     /** 
  188.      * 格式化后的缓存文件路径 
  189.      * 
  190.      * @param  string $id 缓存id 
  191.      * @return string 缓存文件名(包括路径) 
  192.      */ 
  193.     protected function _file($id) 
  194.     { 
  195.      $self = & self::getInstance(); 
  196.         $fileName = $self->_idToFileName($id); 
  197.         return $self->_options['cache_dir'] . $fileName; 
  198.     }    
  199.     
  200.     /** 
  201.      * 格式化后的缓存文件名字 
  202.      * 
  203.      * @param  string $id 缓存id 
  204.      * @return string 缓存文件名 
  205.      */ 
  206.     protected function _idToFileName($id) 
  207.     { 
  208.      $self = & self::getInstance(); 
  209.         $self->_id = $id; 
  210.         $prefix = $self->_options['file_name_prefix']; 
  211.         $result = $prefix . '---' . $id; 
  212.         return $result; 
  213.     }   
  214.     
  215.     /** 
  216.      * 判断缓存是否存在 
  217.      * 
  218.      * @param  string $id Cache id 
  219.      * @return boolean True 缓存存在 False 缓存不存在 
  220.      */ 
  221.     static function test($id) 
  222.     { 
  223.      $self = & self::getInstance(); 
  224.         $file = $self->_file($id); 
  225.         
  226.         if (!is_file($file)) { 
  227.             return false; 
  228.         } 
  229.         
  230.         return true; 
  231.     } 
  232.     
  233.     /** 
  234.      * 得到缓存信息 
  235.      * 
  236.      * @param  string $file 缓存路径 
  237.      * @return string 缓存内容 
  238.      */ 
  239.     protected function _fileGetContents($file) 
  240.     { 
  241.         if (!is_file($file)) { 
  242.             return false; 
  243.         } 
  244.         return include $file; 
  245.     }     
  246.     
  247.     /** 
  248.      * 清除所有缓存 
  249.      * 
  250.      * @return void 
  251.      */    
  252.     static function clear() 
  253.     { 
  254.      $self = & self::getInstance(); 
  255.      $self->save('CLEAR_ALL',self::CLEAR_ALL_KEY); 
  256.     }   
  257.  
  258.     /** 
  259.      * 清除一条缓存 
  260.      * 
  261.      * @param string cache id  
  262.      * @return void 
  263.      */   
  264.     static function del($id) 
  265.     { 
  266.   $self = & self::getInstance(); 
  267.      if(!$self->test($id)){ 
  268.       // 该缓存不存在 
  269.       return false; 
  270.      } 
  271.      $file = $self->_file($id); 
  272.      return unlink($file); 
  273.     } 
  274. } 

存入数据,代码如下:

  1. <?php 
  2. $config = array( 
  3.  'name' => 'xiaojiong', 
  4.  'qq'   => '290747680', 
  5.  'age'  => '20', 
  6. ); 
  7. //第一个参数 缓存data 
  8. //第二个参数 缓存id 
  9. //第三个参数 cache_life 0 永不过期(cache::clear()清空所有除外) 默认cache_life 为option_cache_life 
  10. cache::save($config,'config',0); 

载入数据,代码如下:

  1. <?php 
  2. //只有一个参数 cache_id 
  3. $config = cache::load('config'); 
  4. 清空缓存 
  5. <?php 
  6. //清空指定缓存 
  7. cache::del('config'); 
  8. //清空所有缓存 
  9. cache::clear(); 
  10. cache信息配置 
  11. //在执行所有cache_func前调用 
  12. $_options = array( 
  13.     'cache_dir' => './cache', //缓存文件目录 
  14.     'file_name_prefix' => 'cache',//缓存文件前缀 
  15.     'file_life'  => 100000, //缓存文件生命 
  16. ); 
  17. cache::setOptions($options); 
  18. //再执行 就会按着新配置信息执行,否则是默认信息 
  19. cache::save($arr,'arr'); 

这个方法貌似不合理,感兴趣的朋友可以加以改进。希望本文所述对大家的PHP程序设计有所帮助。

 



出处:http://www.phpfensi.com/php/20210427/14625.html


相关教程