zoukankan      html  css  js  c++  java
  • 简单的页面级缓存类

    <?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 );
                   }
               }
                                            
          }
    }
    ?>

  • 相关阅读:
    form 表单提交被拦截的问题处理方法
    GitLab篇之备份还原
    GitLab篇之Linux下环境搭建
    如何管理我的开发团队
    基于静态站点内容动态推送的方案
    一个小白的程序之路(自身经历)
    敏捷开发方法学及应用
    PMBOK项目管理九大知识领域和五大流程 --美国IT项目管理硕士笔记(二)
    IT项目为什么失败 --美国IT项目管理硕士笔记(一)
    五年.net程序员Java学习之路
  • 原文地址:https://www.cnblogs.com/kuyuecs/p/1393628.html
Copyright © 2011-2022 走看看