<?php
/**
* Name: WriteCache
* Author: Jeff Jing
* Description: A class for Write cache to html
* DateTime: 2009-09-26 16:33:06
* Version: 1.0.0
*/
# 配置参数
$configArr=array();
$configArr['leftDilimiter']='<{';
$configArr['rightDilimiter']='}>';
$configArr['dir']='./html/';
class statiker{
private $content;
private $config;
public function __construct($tpl){ // 构造参数为模板文件
global $configArr;
$this->config=$configArr;
$this->content= file_get_contents ($tpl);
$this->clearSpace();
//var_dump($this->content);
}
private function clearSpace(){
/**@ 去掉分隔符与数据之间的空格
*/
while(strpos($this->content,' '.$this->config['rightDilimiter'])!==false && strpos($this->content,$this->config['leftDilimiter'].' ')!==false){
$this->content=str_replace(' '.$this->config['rightDilimiter'],$this->config['rightDilimiter'],$this->content);
$this->content=str_replace($this->config['lefDilimiter'].' ',$this->config['rightDilimiter'],$this->content);
}
}
public function replace($src,$des){
/**@ 将模板中的变量替换
* @param $src: 模板中的变量
* @param $des: 要替换的变量
主要供内部调用,不建议直接使用
*/
$this->content=str_replace($src,$des,$this->content);
}
public function writeData($name,$data){
/**@ 将实际的变量替换
* @param $name: 模板中的变量
* @param $data: 要替换的变量,可以是一维数组,暂不支持二维数组
*/
if(is_array($data)){
foreach($data as $key=>$value){
$src=$this->config['leftDilimiter'].'$'.$name.'.'.$key.$this->config['rightDilimiter'];
$this->replace($src,$value);
}
}
if(is_numeric($data) || is_string($data)){
$src=$this->config['leftDilimiter'].'$'.$name.$this->config['rightDilimiter'];
$this->replace($src,$data);
}
}
public function show($html){
/**@ 将模板写入文件
* @param $html: 将缓存写入文件
*/
$cachedir = $this->config['dir'];
$cachefile = $cachedir.$html;
//echo $cachefile;
if(!is_dir($cachedir)) {
@mkdir($cachedir, 0777);
}
if(file_exists($cachefile)){ // 如果文件已存在,先将文件删除
unlink($cachefile);
}
var_dump($html);
if(@$fp = fopen($cachefile, 'w')) {
@fwrite($fp, "<!-- created by /writeHtml.php \r\n Date: ".date("Y-m-d h:i:s")." -->\n".$this->content);
@fclose($fp);
@chmod($cachefile, 0777);
} else {
echo 'Can not write file Pls check the directory '.$configArr['dir'];
exit;
}
}
}
?>
|