最简单缓存类

最简单缓存类,改自于smarttemplate,块级缓存使用也同样
例子:
require 'SuCache.cls.php';
echo '缓存前',date('Y-m-d H:i:s', time());
$c=new SuCache( './cache.c.php',3);
$c->start();
echo '<br>可能是缓存',date('Y-m-d H:i:s', time());

<?php
/**
 * 从smarttemplate里改写的缓存类,修改后没详细测试,使用前请测试
 * @author suxiang@126.com
 */
class SuCache
{
    private $file;//缓存文件
    private $timeout=600;//缓存时间10分钟
    private $force=FALSE;//强制写入缓存

    /**
     * @prama string $file存入缓存的文件
     * @prama integer $timeout 缓存时间
     * @force bool 如果在缓存时间内是否强制写入缓存,默认FALSE是读缓存
     */
    public function  __construct($file,$timeout=0,$force=FALSE)
    {
           $filepath=realpath(dirname($file));
        if( ! $filepath || ! is_writable($filepath))
        {
            die('<h3>要缓存的目录不存在或不可写</h3>');
        }

        $this->file=$filepath . '/' . basename($file);

        if($timeout)
            $this->timeout=intval($timeout);
        $this->force=$force;
    }

    /**
     * @prama string $content要写入的内容,空则读缓冲区
     */
    public function start($content='')
    {
        if(''!=$content){
            return    $this->write($content);
        }
        if (!$this->force && $output = $this->read($this->file,$this->timeout))
        {
            exit ($output);//支持块缓存
        }
        else
        {
            ob_start( array( $this, 'callback' ) );
        }
    }


    private function  read(  )
    {
        $filemtime=@filemtime($this->file);
        if( ! $filemtime)
        {
            return ;
        }

        if (!$this->timeout || (time() - $filemtime ) < $this->timeout)
        {
            return file_get_contents($this->file);
        }
    }


    private function write( $content='')
    {
        file_put_contents($this->file,$content);
    }

    //回调函数 必须是public访问
    public function callback(  $buffer )
    {
        $this->write( $buffer );
        return $buffer;
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值