基于phplib template的缓存类

本类基于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;
}
}
?>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值