ECMALL源码阅读六:模板引擎

ECMALL采用了自己编写的模板解析对象template(eccore/view/template.php),来实现代码与表现的分离。
当我们执行display方法时,实现运行的是template对象的display方法。 template对象读取HTML文件,并且解析其中的模板语言,然后输出。

<?php
	$this->assign("goods_list",$goods);
	$this->display("goods.html");
?>

display方法调用的其实是PHP内核函数eval,也就是说执行模板解析的其实是eval方法。
eval参数前面加上’?>’字符串,可以执行HTML跟PHP的混合代码,并且输出。

模板解析(eccore/view/template.php)

<?php
function _eval($content)
{
	/*打开输出控制缓冲*/
	ob_start();
	/*解析模板*/
	eval('?' . '>' . trim($content));
	$content = ob_get_contents();
	ob_end_clean();

	return $content;
}
?>

而把模板语言转化成标准的HTML跟PHP语言的,是template对象的一系列方法。比如:

<?php
switch ($tag_sel)
{
	case 'if':

		return $this->_compile_if_tag(substr($tag, 3));
		break;

	case 'else':

		return '<?php else: ?>';
		break;

	case 'elseif':

		return $this->_compile_if_tag(substr($tag, 7), true);
		break;

	case 'foreachelse':
		$this->_foreachmark = 'foreachelse';

		return '<?php endforeach; else: ?>';
		break;

	case 'foreach':
		$this->_foreachmark = 'foreach';

		return $this->_compile_foreach_start(substr($tag, 8));
		break;
}
?>

这段代码把模板语言if、else、foreach等转化成了标准的PHP语言。我们可以在其中加入自己的代码定义自己喜欢的模板语言。
‘$this->assign(“goods_list”,$goods);‘执行的是template对象的assign方法,这是为了把数据传递给template对象,在模板解析时,会输出这些数据。

<?php
function assign($tpl_var, $value = '')
{
	if (is_array($tpl_var))
	{
		foreach ($tpl_var AS $key => $val)
		{
			if ($key != '')
			{	
				/*把数据保存到template属性*/
				$this->_var[$key] = $val;
			}
		}
	}
	else
	{
		if ($tpl_var != '')
		{
			/*把数据保存到template属性*/
			$this->_var[$tpl_var] = $value;
		}
	}
}
?>