您好,欢迎访问一九零五行业门户网

自个儿动手写一个简单的php模板引擎

自己动手写一个简单的php模板引擎
模板引擎中最核心的思想是:将模板中的变量编译为php的变量进行输出。
例如:demo.tpl
{$data}{$title}

那么模板引擎就要将{$data} {$title} 编译为
要实现这个功能使用正则替换就可以了:
$content = '{$data}{$title}';$pattern = /\{\\$([a-za-z_][a-za-z0-9_]*)\}/;$content = preg_replace($pattern,'tmpvalue[$1] ?>',$content);echo $content; //
这就是php模板引擎的核心功能了。下面是我写的一个简单的php模板引擎
首先是temptool.class.php 它的作用的提供模板引擎需要用到的一些小工具
error[$k] = $v; }else { exit('temptool.class.php的error方法收到了不确定的参数错误!'); } } /** * 获取错误信息 **/ public function geterror() { foreach($this->error as $k=>$v) { echo $k.$v.'
'; } } }?>
然后是template.class.php 它的作用是提供模板引擎应该有的功能
'template/', // 模板文件目录 'cmpdir'=>'compile/', // 编译文件目录 'cachedir'=>'cache/', // 缓存文件目录 'tmpsuffix' =>'.tpl', // 模板文件后缀 'cachesuffix' =>'.html', // 缓存文件后缀 'caching' =>false // 是否开启缓存 ); private $tmpfile; // 模板文件 private $cmpfile; // 编译文件 private $cachefile; // 缓存文件 private $tmpvalue = array(); // 变量值栈 public function __construct($config = null) { // 同步配置 if(is_array($config)) { $this->config = array_merge($this->config,$config); } // 检查模板编译缓存目录是否存在不存在创建 if( !$this->checkdir($this->config['tmpdir']) || !$this->checkdir($this->config['cmpdir']) || !$this->checkdir($this->config['cachedir']) ) { exit; } } /** * 检查目录是否存在不存在自动创建 **/ private function checkdir($dir) { if(!is_dir($dir)) { if(!mkdir($dir)) { $this->errorlog[] = array('创建文件夹失败:'=>$dir); return false; } } return true; } /** * 像模板中分配变量 * **/ public function assign($k,$v) { if(!empty($k) && !empty($v)) { $this->tmpvalue[$k] = $v; }else { $this->error('分配变量失败:','分配到模板中变量的key或者value为空!'); } } /** * 编译文件 **/ public function display($tmpfile) { // 获取模板文件 $tmpfile = $this->config['tmpdir'].$tmpfile.$this->config['tmpsuffix']; // 获取编译文件 $cmpfile = $this->config['cmpdir'].md5($tmpfile.'compile').'.php'; if(!file_exists($tmpfile)) { $this->error('模板文件不存在:',$tmpfile.'不存在'); } // 当编译文件不存在或者是模板文件被修改过了才重新编译 if(!file_exists($cmpfile) || filemtime($cmpfile) cmp($tmpfile,$cmpfile); } // 是否开启缓存 if($this->config['caching']) { // 获取缓存文件 $cachefile = $this->config['cachedir'].md5($tmpfile.'cache').$this->config['cachesuffix']; // 当缓存文件不存在或者是模板文件被修改过重新生成缓存文件 if(!file_exists($cachefile) || filemtime($cachefile) error('编译文件生成失败:',$cachefile); } } //载入缓存文件 include $cachefile; }else { // 载入编译文件 include_once $cmpfile; } }}
compile.class.php  编译类将模板文件编译为php文件
error(文件读取失败:,$tmpfile); } $pattern = /\{\\$([a-za-z_][a-za-z0-9_]*)\}/; $this->content = preg_replace($pattern,'tmpvalue[$1] ?>',$content); $this->parse($cmpfile); } /** * 将编译好的内容写入文件 **/ public function parse($cmpfile) { if(!file_put_contents($cmpfile,$this->content)){ $this->error('文件写入失败:',$cmpfile); } }}?>
下面进行一下测试:
1. 新建一个 template 文件夹 在里面写 一个模板 demo.tpl
{$data}{$title}

2.新建一个demo.php
true);include_once template.class.php;$tmp = new template($config);$tmp->assign('data','ccc');$tmp->assign('title','这时测试用例');$tmp->display('demo');
结果输出 ccc这时测试用例  
可以看一下cache目录和 compile目录下  会生成一个缓存文件 和一个编译文件
这时就成功了
其它类似信息

推荐信息