一个简单的PHP缓存功能

php

<?php
class Cache{
    private $status = false;
    static $close = false;
    function __construct(){
        global $__CACHE;
        if(isset($__CACHE) && 'START'==$__CACHE){//在需要缓存的页面定义$__CACHE变量并设置值为START
            $this->status = true;
        }
        if($this->status)$this->start();       
    }
    private function start(){
        $this->check_file();
        ob_start('Cache::callback');
    }
    public function stop(){//如果需要立即结束则调用,可不调用
        if(!$this->status)return;
        ob_end_flush();
        exit;
    }
    public function clean(){//删除缓存目录
        $list = glob(CACHE_PATH."*");
        foreach($list as $f){
            unlink($f);
        }
    }
    private function check_file(){//检测缓存是否存在,get_config('cache_time')为获取缓存时间,单独替换
        $file = CACHE_PATH.md5(now_url());//CACHE_PATH为缓存文件目录,now_url()为当前页面url,
        if(is_file($file) && filemtime($file)+get_config('cache_time')>time()){
            $content = file_get_contents($file);
            send_header();
            header('Content-Length: '.filesize($file));
            die($content);
        }
    }
    static function callback($content){
        $content = Cache::compress_html($content);
        Cache::make_cache_file($content);
        return $content;
    }
    static function make_cache_file($content){
        if(Cache::$close)return;
        $file = CACHE_PATH.md5(now_url());
        file_put_contents($file,$content);
    }
    static function compress_html($string) {//简单的压缩数据
        $string = str_replace("\r\n", '', $string); //清除换行符  
        $string = str_replace("\n", '', $string); //清除换行符  
        return str_replace("\t", '', $string); //清除制表符  
    }
}
?>

6条评论在“一个简单的PHP缓存功能”

回复 伺服电机   取消