miketwais

work up

mvc框架模板引擎原理及实现

模板引擎我们并不陌生,常见的有Smarty模板引擎,另外我们经常使用的MVC框架中也有用到模板引擎,当然框架中是自己实现的模板引擎,模板引擎的原理大多都是一样的。

即:我们访问php文件的时候,php文件去加载模板引擎,模板引擎再去加载模板,并通过程序替换模板中的变量,并生成一个“编译”文件,然后在访问的php文件中引入这个编译文件来输出。这个类似“缓存”,当再次访问这个文件的时候,如果该编译文件存在且未被改动过,则直接加载,否则重新编译。

下面简单实现一个模板引擎:

文件结构

--templates

----tpl.html

--templates_c

--mytpl.class.php

--testtpl.php  

首先,自定义一个模板引擎。

mytpl.class.php

<?php
class mytpl{
 
 private $template_dir;
 private $compile_dir;
 private $arr_var=array();

public function __construct($template_dir="./templates",$compile_dir="./templates_c")
{
    $this->template_dir = rtrim($template_dir,'/').'/';
    $this->compile_dir = rtrim($compile_dir,'/').'/';
}

public function assign($tpl_var.$value)
{
    $this->arr_var[$tpl_var] = $value;
}

public function display($fileName)
{
    $tplFile = $this->template_dir.$fileName;
    if(!file_exists($tplFile)){
    return false;
    }
    $comFileName=$this->compile_dir."com_".$fileName.".php";

    if(!file_exists($comFileName) || filemtime($comFileName)< filemtime($tplFile)){
    $repContent=$this->tmp_replace(file_get_contents($tplFile));
    file_put_contents($comFileName,$repContent);
    }
    include $comFileName;
}
private function tmp_replace($content){

    $pattern=array(
    '/\{\s*\$([a-zA-Z_]\w*)\s*\}/i'
    );
    $replacement=array(
    '<?php echo $this->arr_var["${1}"]; ?>'
    );
    $repContent=preg_replace($pattern,$replacement,$content);
    return $repContent;
}

}
?>
View Code

然后,使用模板引擎

testtpl.php

<?php
include"mytpl.class.php";
$title="this is title";
$content="this is content";
$tpl=new mytpl();
$tpl->assign("title",$title);
$tpl->assign("content",$content);
$tpl->display("tpl.html");
?>
View Code

最后,创建一个模板文件

tpl.html放在templates文件夹中

<html>
<head>Welcome</head>
<body>
    <h1>{$title}</h1>
     <hr />
     <p>{$content}</p>
</body>
</html>

其实,模板引擎的关键就是,简单标签代替php代码,使逻辑代码和页面设计分离,同时加入文件缓存等机制。

posted @ 2015-05-12 23:14  MasonZhang  阅读(1288)  评论(0)    收藏  举报