浅析PHP模板引擎之二

上篇文章我简要的介绍下模板引擎的运行机理,但是过于简单不太实用,下面我继续扩展这一问题,并使它成为轻量型引擎。

首先我们建立三个目录 ./templates ./templates_c    ./lib 这三个目录分别放模板文件、经过编译后生成的文件、引擎代码文件

下面放上运行原理图:

下面写上各个部分代码:

1.模板引擎template.class.php代码:

< ?php  class template{  private $template_c;  private $data=array();  public function __set($name,$value){  if(!array_key_exists($name,$this->data)){
$this->data[$name]=$value;
}else{
$this->data[$name]=$value;
}

}
public function display($templatename){
$this->template_c=file_get_contents('./templates/'.$templatename);
foreach($this->data as $name => $value){

$this->template_c=str_replace('{'.$name.'}',$value,$this->template_c);

}
echo $this->template_c;

}

}

模板test.tpl代码:

我的名字是 {name}
 手机号 {telephone}
 性别{sex}
 口头禅是{say}

index.php代码:

< ?php  Header('Content-type:text/html;charset=utf-8'); require_once  "./lib/template.class.php"; $template= new template; $template->name="lvxinwei";
$template->telephone=15151827622;
$template->sex="男";
$template->say="我勒个去";
$template->display('test.tpl');

显示效果:
我的名字是 harold
手机号 151518276xx
性别男
口头禅是我勒个去
在第三节,我会继续扩展该问题,使之能进行智能化的页面缓存;

Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据