1. 编译
把模板文件中的变量,函数用正式表达式替换成php变量,并把替换后的内容保存到编译文件里
实现代码:compile函数
2. 缓存
如果开启了缓存,并且缓存文件不存在或缓存文件存在但是缓存文件修改时间小于编译文件修改时间,则包含编译文件,并把把内容保存到缓存文件里头,否则包含缓存文件
实现代码:cache函数
git代码:https://gitlab.com/mzc/miniSmarty
以下为具体实现类:
<?php
class miniSmarty
{
public $tpl_vars = array();
public $templates = "./templates/";
public $templates_c = "./templates_c/";
public $cache = "./cache/";
public $caching = false;
public function assign($var,$value=null){
if(!empty($var)){
$this->tpl_vars[$var] = $value;
}else{
exit("分配的变量名称不能为空");
}
}
public function display($templateName){
$templateFile = $this->templates.$templateName;
if(!file_exists($templateFile)){
exit("模板文件不存在");
}else{
$compileFile = $this->templates_c.$templateName.'.php';
if(!file_exists($compileFile)||(file_exists($compileFile)&&filemtime($compileFile)<filemtime($templateFile))){
$this->compile($templateFile, $compileFile);
}
$this->cacheFile($templateName, $compileFile);
}
}
public function compile($templateFile,$compileFile){
$templateContent = file_get_contents($templateFile);
$pattern = array(
'/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/'
);
$replace = array(
'<?php echo $this->tpl_vars["${1}"]?>'
);
$newContent = preg_replace($pattern, $replace, $templateContent);
if(!file_put_contents($compileFile,$newContent)){
exit("编译模板文件出错");
}
}
public function cacheFile($templateName,$compileFile){
if($this->caching){
$cacheFile = $this->cache.md5($templateName).$templateName."html";
if(!file_exists($cacheFile)||filemtime($cacheFile)<filemtime($compileFile)){
include_once($compileFile);
$content = ob_get_clean();
file_put_contents($cacheFile,$content);
}
include_once($cacheFile);
}else{
include_once($compileFile);
}
}
}