php模板引擎技术简单实现
用了smarty,tp过后,也想了解了解其模板技术是怎么实现,于是写一个简单的模板类,大致就是读取模板文件->替换模板文件的内容->保存或者静态化
tpl.class.php主要解析
assign方法实现
/** *模板赋值操作 *@parammixed$tpl_var如果是字符串,就作为数组索引,如果是数组,就循环赋值 *@parammixed$tpl_value当$tpl_var为string时的值,默认为null */ publicfunctionassign($tpl_var,$tpl_value=null){ if(is_array($tpl_var)&&count($tpl_var)>0){ foreach($tpl_varas$k=>$v){ $this->tpl_vars[$k]=$v; } }elseif($tpl_var){ $this->tpl_vars[$tpl_var]=$tpl_value; } }
fetch方法实现
/** *生成编译文件 *@paramstring$tplFile模板路径 *@paramstring$comFile编译路径 *@returnstring */ privatefunctionfetch($tplFile,$comFile){ //判断编译文件是否需要重新生成(编译文件是否存在或者模板文件修改时间大于编译文件的修改时间) if(!file_exists($comFile)||filemtime($tplFile)>filemtime($comFile)){ //编译,此处也可以使用ob_start()进行静态化 $content=$this->tplReplace(file_get_contents($tplFile)); file_put_contents($comFile,$content); } }
简单编译方法:按照规则进行正则替换
/** *编译文件 *@paramstring$content待编译的内容 *@returnstring */ privatefunctiontplReplace($content){ //转义左右定界符正则表达式字符 $left=preg_quote($this->left_delimiter,'/'); $right=preg_quote($this->right_delimiter,'/'); //简单模拟编译变量 $pattern=array( //例如{$test} '/'.$left.'\$([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)'.$right.'/i' ); $replace=array( '<?phpecho$this->tpl_vars[\'${1}\'];?>' ); //正则处理 returnpreg_replace($pattern,$replace,$content); }
display=fetch+echo
/** *输出内容 *@paramstring$fileName模板文件名 */ publicfunctiondisplay($fileName){ //模板路径 $tplFile=$this->template_dir.'/'.$fileName; //判断模板是否存在 if(!file_exists($tplFile)){ $this->errorMessage='模板文件不存在'; returnfalse; } //编译后的文件 $comFile=$this->compile_dir.'/'.md5($fileName).'.php'; $this->fetch($tplFile,$comFile); include$comFile; }
其他属性
//模板文件存放位置 private$template_dir='templates'; //编译文件存放位置 private$compile_dir='compiles'; //左定界符 private$left_delimiter='{'; //右定界符 private$right_delimiter='}'; //内部临时变量,存储用户赋值 private$tpl_vars=array(); //错误信息 private$errorMessage=''; /** *修改类属性的值 *@paramarray$configs需要修改的相关属性及值 *@returnbool */ publicfunctionsetConfigs(array$configs){ if(count($configs)>0){ foreach($configsas$k=>$v){ if(isset($this->$k)) $this->$k=$v; } returntrue; } returnfalse; }
测试
模板文件testTpl.html
<!DOCTYPEhtml> <htmllang="en"> <head> <metacharset="UTF-8"> <title>test_tpl_demo</title> </head> <body> {$name}:{$age}:{$message} </body> </html> 运行文件test_tpl.php <?php require'Tpl.class.php'; $tpl=newTpl(); $tplarr=array( 'name'=>'waited', 'age'=>'100' ); $tpl->assign($tplarr); $tpl->assign('message','thisisademo'); $tpl->display('testTpl.html'); ?>
输出:waited:100:thisisademo
生成编译文件:972fa4d270e295005c36c1dbc7e6a56c.php
以上就是本文的全部内容,希望对大家的学习有所帮助。