您的位置:首页 > 编程语言 > PHP开发

php学习笔记(三十三)php自定义模板引擎的实现

2013-01-06 16:32 627 查看
自己实现简单的模板引擎:方面php的逻辑与页面进行分离

模板类:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title><{$title}></title>
</head>
<body>
<{$content}>
</body>
</html>


调用的页面:

<?php
include "mytpl.class.php";

$tpl = new MyTpl("./templates/","./templates_c");
//程序简单方式
$title="这是一个文字标题,从数据库中获取";
$content = "这是内容";

$tpl->assign("title",$title);
$tpl->assign("content",$content);

$tpl->display("mysmarty.html");
?>


转换页面:

<?php
header("ContentType=text/html;charset=UTF-8");
class MyTpl{
private $template_dir;
private $compile_dir;
private $tpl_vars=array();
/**
* 模板路径和编译后的路径
* @param 模板路径 $template_dir
* @param 编译路径 $compile_dir
*/
function  __construct($template_dir="./templates",$compile_dir="./templates_c"){
//添加最后的/
$this->template_dir = rtrim($template_dir,"/").'/';
$this->compile_dir = rtrim($compile_dir,"/").'/';;
}

/**
* 将变量输入到数组中
* @param unknown_type $tpl_var
* @param unknown_type $value
*/
public function assign($tpl_var,$value=NULL){
if($tpl_var!=""){
$this->tpl_vars[$tpl_var]=$value;
}
}
/**
* 显示最后生成的文件
* @param 模板文件 $fileName
*/
public function display($fileName){
//模板文件
$tplfile = $this->template_dir.$fileName;
if (!file_exists($tplfile)) {
return false;
}
//编译的文件名
$confileName = $this->compile_dir."com_".$fileName.".php";

if (!file_exists($confileName) || filemtime($confileName)<filemtime($tplfile)) {
$repContent = $this->tpl_replace(file_get_contents($tplfile));
file_put_contents($confileName, $repContent);
}
//显示输出
include $confileName;
}
/**
* 替换模板后返回
* Enter description here ...
* @param unknown_type $content
*/
private function tpl_replace($content){
//匹配正则表达式
$pattern = array('/\<{\s*\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)\s*\}\>/i');
$replacement = array('<?php echo $this->tpl_vars["${1}"]; ?>');
$repContent = preg_replace($pattern, $replacement, $content);
return $repContent;
}
}
?>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: