一个编译型的PHP模板引擎大致实现过程
JTemplate.class.php
001
<?php
002
/**
003
* <a href="http://my.oschina.net/arthor" target="_blank" rel="nofollow">@author</a> Jiawei
004
* @Completed in 2012-6-29 0:23
005
*/
006
class JTemplate{
007
//通过assign函数传入的变量临时存放数组
008
private $templateVar = array();
009
//模板目录
010
private $templateDir = '';
011
//编译目录
012
private $templateCompileDir = '';
013
014
private $fileName = '';
015
/**
016
* 构造函数
017
* @param string $templateDir 模板目录
018
* @param string $templateComplieDir 模板编译目录
019
*/
020
public function __construct($templateDir,$templateComplieDir){
021
$this->templateDir = $templateDir;
022
$this->templateCompileDir = $templateComplieDir;
023
}
024
/**
025
* 显示模板
026
* @param string $fileName 模板文件名
027
*/
028
public function display($fileName){
029
$this->fileName = $fileName;
030
if(file_exists($this->templateDir.'/'.$this->fileName)){
031
$compileFileName = $this->templateCompileDir.'/'.$this->file_safe_name().'.php';
032
if(!file_exists($compileFileName) || filemtime($compileFileName)< filemtime($this->templateDir.'/'.$this->fileName)){
033
$this->del_old_file();
034
$this->compile();
035
}
036
extract($this->templateVar);
037
include $compileFileName;
038
}else{
039
$this->error('Sorry,the template file '.$this->fileName.' does not exist!!');
040
}
041
}
042
/**
043
* 获取编译文件名
044
*/
045
private function get_compile_file(){
046
$compileFile = explode('.',$this->fileName);
047
unset($compileFile[count($compileFile)-1]);
048
return implode('.',$compileFile);
049
}
050
/**
051
* 编译
052
*/
053
private function compile(){
054
$fileHandle = @fopen($this->templateDir.'/'.$this->fileName, 'r');
055
while(!feof($fileHandle)){
056
$fileContent = fread($fileHandle,1024);
057
}
058
fclose($fileHandle);
059
$fileContent = $this->template_replace($fileContent);
060
//$compileFile = $this->get_compile_file($fileName);
061
$fileHandle = @fopen($this->templateCompileDir.'/'.$this->file_safe_name().'.php','w');
062
if($fileHandle){
063
fwrite($fileHandle, $fileContent);
064
fclose($fileHandle);
065
}else{
066
$this->error('Sorry,Compile dir can not write!');
067
}
068
}
069
/**
070
* 模板传值
071
* @param string $valueName 模板中使用的变量名
072
* @param $value 变量值
073
*/
074
public function assign($valueName,$value){
075
$this->templateVar[$valueName] = $value;
076
}
077
078
/**
079
* 模板正则替换
080
* @param string $content 替换内容
081
* <a href="http://my.oschina.net/u/556800" target="_blank" rel="nofollow">@return</a> string 替换过后的内容
082
*/
083
private function template_replace($content){
084
$orginArray = array(
085
'/<!--loop\s+\$(\w+)\s+\$(\w+)-->/s',
086
'/<!--loop\s+\$(\w+)\s+\$(\w+)\s+\$(\w+)-->/s',
087
'/<!--elseloop-->(.+?)<!--endloop-->/s',
088
'/<!--endloop-->/s',
089
'/<!--if\s+\((.+?)\)-->/s',
090
'/<!--endif-->/s',
091
'/<!--elseif\s+\((.+?)\)-->/s',
092
'/<!--else-->/s',
093
'/\{P:(.+?)\:}/s',
094
'/\{C:(\w+)\}/s',
095
补充:Web开发 , php ,