<?php
	require_once './cls_MiniSmarty.php';
	$miniSmarty = new MiniSmarty();
	//传递数据
	$miniSmarty->assign("title","hello minismarty!");
	$miniSmarty->assign("content","<font color='red'>this is content!</font>");
	//传递数据到哪个页面显示
	$miniSmarty->display("intro.tpl");
?>3.编写intro.tpl文件<!--这是个模板文件-->
<html>
<head>
<meta http-equiv="Content-Language" content="en" />
<meta name="GENERATOR" content="PHPEclipse 1.0" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>{$title}</title>
</head>
<body bgcolor="#FFFFFF" text="#000000" link="#FF9966" vlink="#FF9966" alink="#FFCC99">
{$content}
</body>
</html>
<?php
/**
 *
 * 原本是通过smarty模板引擎给模板提供数据的
 * 现在自己模仿写一个模板,给模板提供数据的类
 * smarty运行时,读取模板文件,将模板文件替换成可运行的php文件。服务器真正运行的文件是处理后的文件。
 */
class MiniSmarty {
	//模板文件路径
	var $template_dir = "./templates/";
	//模板文件被替换后的文件路径
	var $templates_c_dir = "./templates_c/";
	//存放变量值
	var $tpl_vars = array ();
	//主要模拟2个方法
	/**
	 * 添加数据
	 *	参数1:键
	 *	参数2:值,默认为null
	 */
	function assign($tpl_var, $var = null) {
		if ($tpl_var != '') {
			$this->tpl_vars[$tpl_var] = $var; //将数据添加到数组中
		}
	}
	/**
	 * 显示数据
	 * 参数1:显示到哪个模板文件中
	 */
	function display($tpl_file) {
		//获得模板文件的路径
		$tpl_file_path = $this->template_dir . $tpl_file;
		//获得模板文件被编译后的文件路径
		$compile_file_path = $this->templates_c_dir . "com_" . $tpl_file . ".php";
		//判断文件是否存在
		if (!file_exists($tpl_file_path)) {
			return false;
		}
		//不用每次都生成编译文件,只有编译文件不存在或者模板文件被修改了才生成新的编译文件
		//相当于缓存了编译文件
		//filemtime函数:获得文件的生成时间
		if (!file_exists($compile_file_path) || filemtime($tpl_file_path) > filemtime($compile_file_path)) {
			//读取模板文件的内容
			$fpl_file_content = file_get_contents($tpl_file_path);
			$newStr = myReplace($fpl_file_content);
			//将替换后的字符串生成新的文件,也就是编译后的文件
			file_put_contents($compile_file_path, $newStr);
		}
		//引入编译后的文件
		include $compile_file_path;
	}
	/**
	 * 对模板文件中的内容进行替换,获得新的字符串
	 */
	function myReplace($fpl_file_content) {
		$pattern = array (
			'/\{\s*\$([a-zA-Z_][a-zA-Z0-9_]*)\s*\}/i'
		);
		$replace = array (
			'<?php echo $this->tpl_vars["${1}"]  ?>'
		);
		$newStr = preg_replace($pattern, $replace, $fpl_file_content);
		return $newStr;
	}
}
?>
原文:http://blog.csdn.net/z18789231876/article/details/42120389