本文说明了Smarty模板类的内部原理。分享给大家参考,如下:
之前在学习ThinkPHP的时候接触过Smarty模板类,但是一直不知道它的内部实现原理。今天博主终于知道了它的内在原理,其实挺简单的,然后写了一个mini版的Smarty模板类,对了解它的内在原理有很大的帮助。
1.迷你智能类
先编码,再解释。
项目图
迷你马蒂等级代码(MiniSmarty.class.php)
?Php/** *迷你模板类*/class mini smarty { public $ template _ dir=' ';//放置模板文件的目录是public $ compile _ dir=//编译后放置文件的目录public $ TPL _ var=array();//为模板赋值的变量/* * *为模板赋值* @ param str $ key key * @ param mixed $ value * @ return void */public function Assign($ key,$ value){ $ this-TPL _ var[$ key]=$ value;}/* * *编译模板并导入编译后的文件* @ param str $ template file * @ return void */public function display($ template){ $ compile _ file=$ this-compile($ template);包括($ compile _ file);}/* * * * *读取模板文件的内容$ source=file _ get _ contents($ template _ file);//确定编译文件$ compile _ file=$ this-compile _ dir。'/'.$模板。“PHP”需要重新生产;//如果有编译文件,且编译文件的修改时间比模板文件的修改时间长,则无需再次编译,而是直接返回文件路径If(file _ exists($ compile _ file)file mtime($ compile _ file)file mtime($ template _ file)){ return $ compile _ file;}//将{$}解析为?Php echo和其他操作$source=str_replace('{$ ','?php echo $this-tpl_var[ ' ',$ source);$source=str_replace('} ',' '];',$ source);//生成编译文件file _ put _ contents($ compile _ file,$ source);//返回编译后的文件路径返回$ compile _ file}}?测试模板类别代码(testSmarty.php)
?Php//1。引入并创建一个模板实例包括('。/mini smart . class . PHP ');$ Smarty=new minimarty();$Smarty-template_dir='。/template ';$Smarty-compile_dir='。/compile ';//2.分配模板对象$title=“将举行两次会议”;$content='好奶粉,好会议,好消息';$Smarty-assign('title ',$ title);$Smarty-assign('content ',$ content);//3.显示模板$ template=' template.html$ Smarty-display($模板);模板文件(template.html)
!DOCTYPE html html Head meta charset=' utf-8 ' meta http-equiv=' X-UA-Compatible ' content=' IE=edge ' title { $ title }/title link rel='样式表' href=' '/Head body H3 { $ content }/H3/body/html编译文件(template.html.php)
!DOCTYPE htmlhtmlhead元字符集='utf-8 '元http-equiv='X-UA-Compatible '内容='IE=edge '标题?PHP echo $ this-TPL _ var[' title '];/title link rel='样式表' href=''/headbody h3?PHP echo $ this-TPL _ var[' content '];/h3/body/html代码已粘贴。最后,解释一下。在测试模板类(testSmarty.php)文件中,首先引入模板类文件,实例化模板对象,然后分配模板对象,最后显示模板。在模板类(MiniSmarty.class.php)文件中,有三个属性和三个方法。属性有template_dir、compile_dir ' '和tpl_var,分别表示模板文件的路径、编译文件的路径和模板对象的变量。三种方法是赋值、显示和编译,赋值方法是给模板对象赋值,显示方法是编译模板文件并引入(显示)编译后的文件,编译方法是编译模板文件。编译模板文件的过程主要是将模板文件中的{$ tag}解析成?php echo $var?等等。php代码。
2.Smarty原理分析
工作流程
(1)为要显示的全局变量赋值,并将其插入对象内部属性的数组中(2)编译模板并将{$ tag}解析为相应的php echo代码(3)导入编译后的php文件。
使用步骤
(1)Smarty是一个类。如果要使用它,它必须被实例化。(2)为模板赋值。(3)使用显示方法[从编译到输出]
Smarty的缺点
(1)编译模板浪费时间;(2)将变量重新分配给对象的属性会增加开销
更多对Smarty相关内容感兴趣的读者可以查看本网站专题:《smarty模板入门基础教程》、《PHP模板技术总结》、《PHP基于pdo操作数据库技巧总结》、《PHP运算与运算符用法总结》、《PHP网络编程技巧总结》、《PHP基本语法入门教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》、《php常见数据库操作技巧汇总》。
希望本文对基于smarty模板的PHP编程有所帮助。