最简单缓存类,改自于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;
}
}
例子:
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;
}
}