先编写一个MyMiniSmarty的类
<?php
class MiniSmarty {
//模板文件路径
var $template_dir="./templates/";
//指定一个模板文件被替换后的文件
var $complie_dir="./templates_c/";
//存放变量
var $tpl_vars=array();
//模拟两个主要的方法;
function assign($tpl_var,$val=NULL){
if($tpl_var!=''){
$this->tpl_vars[$tpl_var]=$val;
}
}
//读取模板
function display($tpl_file){
//替换可编译的php
$tpl_file_path=$this->template_dir.$tpl_file;
$complie_file_path=$this->complie_dir."com_".$tpl_file.".php";
//判断模板文件是否存在
if(!file_exists($tpl_file_path)){
return false;
}
//没有必要每次都去编译一个新的文件
if(!file_exists($complie_file_path)||filemtime($tpl_file_path)>filemtime($complie_file_path)){
$tpl_file_con=file_get_contents($tpl_file_path);
$pattern=array(
'/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i'
);
$replace=array(
'<?php echo $this->tpl_vars["${1}"]?>'
);
$new_str=preg_replace($pattern, $replace, $tpl_file_con);
file_put_contents($complie_file_path,$new_str);
}
echo 'ok';
include_once $complie_file_path;
}
}
?>
然后在根目录分别创建模板文件夹templates和存放编译后的文件夹templates_c
在templates文件夹中新建一个模板test.tpl
代码如下:
<head>
<title>samrty研究2</title>
</head>
<body>
<h1>{$title}</h1>
<p>helloword^-^</p>
</body>
在index.php文件夹调用MyMiniSmarty类.文件代码如下:
<?php
require_once 'MyMiniSmarty.php';
$test=new MiniSmarty;
$test->assign("title","my first smarty test");
$test->display(test.tpl');
?>
这样一个简单的smarty引擎就完成啦.^-^.