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

自己实现简单的模板引擎:方面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;
		}
	}
?>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值