本类基于phplib template类.
<?php
/*
* cacheTemplate writed by 风随影动Surrey(surreyk@msn.com)
* Programming Language PHP5
* $Id: phplib_template.class.php,v 1.0 2005/03/05 08:51:35 kk Exp $
*
*/
/********************cacheTempalte类*********************************/
class cacheTemplate extends Template
{
/* cache的目录,请保证0777权限*/
protected static $cacheDir = "./cache";
/* cache超时时间,单位秒*/
protected static $timeout = 60;
/*构造函数,使用方法与template类相同*/
public function __construct($root = ".", $unknowns = "remove")
{
$this->Template($root, $remove);
}
/* 设置文件,uniqID为此文件唯一ID,手动指定,请保证同一文件的ID相同*/
public function setFile($handle, $filename, $uniqID)
{
if (!is_array($handle)) {
if ($filename == "") {
throw new templateException("set_file: For handle $handle filename is empty.", 60001);
return false;
}
$this->file[$handle] = $this->filename($filename);
} else {
reset($handle);
while(list($h, $f) = each($handle)) {
$this->file[$h] = $this->filename($f);
}
}
$this->uniqID = $uniqID;
ob_start();
}
/*判断uniqID是否已经被缓存,调用方法 cacheTemplate::isCached(uniqID)*/
public function isCached($uniqID)
{
//return false;
$cacheFile = self::$cacheDir."/".md5($uniqID);
if (file_exists($cacheFile) &&
date("YmdHis") - date("YmdHis", filemtime($cacheFile)) < self::$timeout) {
return true;
} else {
return false;
}
}
/*刷新缓存,即删除uniqID对应文件,调用方法$cacheTemplate->refresh(uniqID)*/
public function refresh($uniqID)
{
if ($this->isCached($uniqID)) {
@unlink($this->cacheDir."/".md5($uniqID));
return true;
}
return false;
}
/*输出缓存内容,调用方法cacheTemplate::printCache(uniqID)*/
public function printCache($uniqID)
{
$cacheFile = self::$cacheDir."/".md5($uniqID);
if (self::isCached($uniqID)) {
$fhandle = @fopen($cacheFile, "rb");
if ($fhandle) {
while(!feof($fhandle)) {
print fgets($fhandle,1024);
}
fclose($fhandle);
return true;
}
}
return false;
}
/*输出模板解析后内容,请务必使用这个函数而不是template中的parse()然后p()*/
public function pparse($target, $handle, $append = false)
{
print $this->parse($target, $handle, $append);
$content = ob_get_contents();
ob_end_flush();
$fhandle = @fopen(self::$cacheDir."/".md5($this->uniqID), "wb");
if ($fhandle) {
fwrite($fhandle, $content);
fclose($fhandle);
}
$this->uniqID = null;
}
}
?>