简单的页面级缓存类

<?php

class AutoCache{     
     private $_CACHE_ROOT = "d:/cache/";           //缓存路径
     private $_CATHE_LIFE = 86400;                    //生命周期,86400秒为一天
     private $_CACHE_SUFFIX = ".html";               //缓存文件扩展名
     private $cache_file_name;                             //缓存文件名
     private $cache_path;                                   //当前文件所存储的路径
     function __construct(){

          //通过md5的前2位命名目录,防止单目录下文件过多
          //如页面还是比较庞大,可取md5的3、4位增加一级目录,单目录文件不多于1000
          $this->cache_file_name = md5( $_SERVER["REQUEST_URI"] ) . $this->_CACHE_SUFFIX;
          $this->cache_path = $this->_CACHE_ROOT . substr( $this->cache_file_name, 0, 2 );
          if( "GET" == $_SERVER["REQUEST_METHOD"] ){
               if( file_exists( $this->cache_path . "/" . $this->cache_file_name ) && time() - filemtime( $this->cache_path . "/" . $this->cache_file_name ) < $this->_CATHE_LIFE ){
                    echo file_get_contents( $this->cache_path . "/" . $this->cache_file_name );
                    exit;
               } else {
                    ob_start( array( &$this, "saveCache" ) );
               }
          }elseif( file_exists( $this->cache_path . "/" . $this->cache_file_name ) ){
               unlink( $this->cache_path . $this->cache_file_name );
          }
     }
                
     function saveCache( $buffer ){
          if( !file_exists( $this->_CACHE_ROOT ) ){
               mkdir( $this->_CACHE_ROOT, 0777 );
          }
          if( !file_exists( $this->cache_path ) ){
               mkdir( $this->cache_path, 0777 );
          }
          file_put_contents( $this->cache_path . "/" . $this->cache_file_name, $buffer, LOCK_EX );
          return $buffer;
     }
                
     function __destruct(){
          chdir( $this->_CACHE_ROOT ) or die( "缓存路径不存在!!" );
          foreach ( glob( "*/*" . $this->_CACHE_SUFFIX ) as $file){
               if( time() - filemtime( $file ) > $this->_CATHE_LIFE ){
                    unlink( $file );
               }
           }
                                        
      }
}
?>

转载于:https://www.cnblogs.com/kuyuecs/archive/2009/02/19/1393628.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值