默默简单的写了一个模板引擎


Posted in PHP onJanuary 02, 2007

引擎文件 

<?php  
/**  
* 默默基于Discuz的模板引擎开发的OOP类模板引擎,可支持模板缓存并生成hash的md5值。由hash值来判断模板是否被修改,假如被修改则重新生成缓存文件,假如没有被修改,则直接调用缓存文件.  
* 版本:1.0.0.1 beta 测试版  
*/  
class mmtp{          var $left_tags="{";  
        var $right_tags="}";  
        var $tp_suffix=".html";  
        var $cache_suffix=".tpl";  
        var $tp_dir="./";  
        var $cache_dir="./";  
        /**  
         * 允许循环嵌套的次数,默认为5  
         *  
         * @var unknown_type  
         */  
        var $nest = 5;      
    /**  
     * 模板路径  
     *  
     * @param unknown_type $tp_dir  
     * @return mmtp  
     */  
        function __setdir($tp_dir){  
                        if(file_exists($tp_dir)){  
                                $this->tp_dir=$tp_dir;  
                        }else{  
                                $this->error("模板路径不存在");  
                        }  
        }  
        /**  
         * 设置缓存目录  
         *  
         * @param unknown_type $cache_dir  
         */  
        function __setcdir($cache_dir){  
                                if(file_exists($cache_dir)){  
                                $this->cache_dir=$cache_dir;  
                        }else{  
                                $this->error("缓存路径不存在");  
                        }  
        }  
    /**  
     * 输出错误信息  
     *  
     * @param unknown_type $msg  
     */  
        function error($msg){  
                print "<div style=\"font-size:12px;color:red;\">".$msg."</div>";  
        }  
        /**  
         * 解析模板  
         *  
         * @param unknown_type $file  
         */  
        function tp($file){  
                $tp_path=$this->tp_dir.$file.$this->tp_suffix;  
                $fp=fopen($tp_path,"rb");  
                if(!$this->file_test($tp_path,"r") && !$this->match_hash($file)){  
                        $template=$this->file_read($tp_path);  
                    $var_regexp = "((\\\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(\[[a-zA-Z0-9_\-\.\"\'\[\]\$\x7f-\xff]+\])*)";  
                    $const_regexp = "([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)";  
                        $template = preg_replace("/([\n\r]+)\t+/s", "\\1", $template);  
                        $template = preg_replace("/\<\!\-\-\{(.+?)\}\-\-\>/s", "{\\1}", $template);  
                        $template = preg_replace("/\{lang\s+(.+?)\}/ies", "languagevar('\\1')", $template);  
                        $template = str_replace("{LF}", "<?=\"\\n\"?>", $template);  
                        $template = preg_replace("/\{(\\\$[a-zA-Z0-9_\[\]\'\"\$\.\x7f-\xff]+)\}/s", "<?=\\1?>", $template);  
                        $template = preg_replace("/$var_regexp/es", "\$this->addquote('<?=\\1?>')", $template);  
                        $template = preg_replace("/\<\?\=\<\?\=$var_regexp\?\>\?\>/es", "\$this->addquote('<?=\\1?>')", $template);  
                          
                        $template = preg_replace("/[\n\r\t]*\{template\s+([a-z0-9_]+)\}[\n\r\t]*/is", "\n<? include('".$this->cache_dir."\\1".$this->cache_suffix."'); ?>\n", $template);  
                        $template = preg_replace("/[\n\r\t]*\{template\s+(.+?)\}[\n\r\t]*/is", "\n<? include('".$this->cache_dir."\\1".$$this->cache_suffix."'); ?>\n", $template);  
                        $template = preg_replace("/[\n\r\t]*\{eval\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? \\1 ?>\n','')", $template);  
                        $template = preg_replace("/[\n\r\t]*\{echo\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? echo \\1; ?>\n','')", $template);  
                        $template = preg_replace("/[\n\r\t]*\{elseif\s+(.+?)\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? } elseif(\\1) { ?>\n','')", $template);  
                        $template = preg_replace("/[\n\r\t]*\{else\}[\n\r\t]*/is", "\n<? } else { ?>\n", $template);  
                        for($i = 0; $i < $this->nest; $i++) {  
                        $template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\}[\n\r]*(.+?)[\n\r]*\{\/loop\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? if(is_array(\\1)) { foreach(\\1 as \\2) { ?>','\n\\3\n<? } } ?>\n')", $template);  
                        $template = preg_replace("/[\n\r\t]*\{loop\s+(\S+)\s+(\S+)\s+(\S+)\}[\n\r\t]*(.+?)[\n\r\t]*\{\/loop\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? if(is_array(\\1)) { foreach(\\1 as \\2 => \\3) { ?>','\n\\4\n<? } } ?>\n')", $template);  
                        $template = preg_replace("/[\n\r\t]*\{if\s+(.+?)\}[\n\r]*(.+?)[\n\r]*\{\/if\}[\n\r\t]*/ies", "\$this->stripvtags('\n<? if(\\1) { ?>','\n\\2\n<? } ?>\n')", $template);  
                        }  
                        $template = preg_replace("/\{$const_regexp\}/s", "<?=\\1?>", $template);  
                        $template = preg_replace("/ \?\>[\n\r]*\<\? /s", " ", $template);  
                        $hash=$this->file_hash($tp_path);  
                        $head_hash="<!-- hash=".$hash." -->";  
                        $foot_time="<!-- time=".(date("Y-m-d G:i:s"))." -->";  
                        $this->file_write($this->cache_dir.$file.".tpl",$head_hash.$template.$foot_time);  
                          
                }  
        }  
          
        /**  
         * 检查文件是否存在并且有读取权限  
         *  
         * @param unknown_type $path  
         */  
        function file_test($path,$method){  
                if(!file_exists($path) || !fopen($path,$method)){  
                        $this->error("模板文件不存在,或没有操作权限");  
                        return false;  
                }  
        }  
        /**  
         * 读取文件内容  
         *  
         * @param unknown_type $path  
         * @return unknown  
         */  
        function file_read($path,$length=0){  
                if(!$this->file_test($path,"r+")){  
                $fp=@fopen($path,"r+");  
                if($length==0){  
                        $contents=@fread($fp,filesize($path));  
                }else{  
                        $contents=@fread($fp,$length);  
                }  
                fclose($fp);  
                return $contents;  
                }  
        }  
          
        /**  
         * 写入文件内容  
         *  
         * @param unknown_type $path  
         * @param unknown_type $puts  
         */  
        function file_write($path,$puts){  
                if(!$this->file_test($path,"w+")){  
                $fp=@fopen($path,"w+");  
                @fwrite($fp,$puts);  
                fclose($fp);  
                }  
        }  
          
        /**  
         * 计算文件的hash  
         *  
         * @param unknown_type $path  
         * @return unknown  
         */  
        function file_hash($path){  
                return md5_file($path);  
        }  
          
        /**  
         * 对比模板文件与缓存文件的hash值  
         *  
         * @param unknown_type $file  
         * @return unknown  
         */  
        function match_hash($file){  
                $read_hash=$this->file_read($this->cache_dir.$file.$this->cache_suffix,46);  
                $html_hash=$this->file_hash($this->tp_dir.$file.$this->tp_suffix);  
                        if(preg_match("/".$html_hash."/i",$read_hash)){  
                        return true;  
                }  
        }  
        function addquote($var) {  
        return str_replace("\\\"", "\"", preg_replace("/\[([a-zA-Z0-9_\-\.\x7f-\xff]+)\]/s", "['\\1']", $var));  
        }  
        function transamp($str) {  
        $str = str_replace('&', '&', $str);  
        $str = str_replace('&amp;', '&', $str);  
        $str = str_replace('\"', '"', $str);  
        return $str;  
}  
        function stripvtags($expr, $statement) {  
        $expr = str_replace("\\\"", "\"", preg_replace("/\<\?\=(\\\$.+?)\?\>/s", "\\1", $expr));  
        $statement = str_replace("\\\"", "\"", $statement);  
        return $expr.$statement;  
}  
}  

$tp=new mmtp();  
$tp->__setdir("./");  
$tp->__setcdir("./cache/");  
$tp->tp("index1");  
$_GET[it]=sdhkadajksdhajdhkajsdhjkasdjkasdhasjdhkjsadhk;  
$name=2;  
$head="欢迎使用MoMo模板引擎";  
include("./cache/index1.tpl");  
?> 

模板index.html 

{$head}
 
模板index1.html
{template index}  
{if $name==1}  
你好  
{else}  
谢谢  
{/if}  

这个模板是默默今天下午写的,写的比较仓促,也许存在漏洞,这个版本只是测试版,以后我会逐渐的去完善,先发出来,当作一个前瞻.

PHP 相关文章推荐
ASP知识讲座四
Oct 09 PHP
用PHP制作的意见反馈表源码
Mar 11 PHP
Windows下利用Gvim写PHP产生中文乱码问题解决方法
Apr 20 PHP
PHP中替换换行符的几种方法小结
Oct 15 PHP
深入解析php中的foreach问题
Jun 30 PHP
php中in_array函数用法分析
Nov 15 PHP
在Mac OS上编译安装Nginx+PHP+MariaDB开发环境的教程
Feb 23 PHP
基于php(Thinkphp)+jquery 实现ajax多选反选不选删除数据功能
Feb 24 PHP
PHP两种实现无级递归分类的方法
Mar 02 PHP
详解Yaf框架PHPUnit集成测试方法
Dec 27 PHP
Laravel中unique和exists验证规则的优化详解
Jan 28 PHP
Laravel6.18.19如何优雅的切换发件账户
Jun 14 PHP
超强分页类2.0发布,支持自定义风格,默认4种显示模式
Jan 02 #PHP
PHP小技巧搜集,每个PHPer都来露一手
Jan 02 #PHP
实例(Smarty+FCKeditor新闻系统)
Jan 02 #PHP
PHP+JS无限级可伸缩菜单详解(简单易懂)
Jan 02 #PHP
PHP文件上传实例详解!!!
Jan 02 #PHP
AJAX for PHP简单表数据查询实例
Jan 02 #PHP
[原创]PHP中通过ADODB库实现调用Access数据库之修正版本
Dec 31 #PHP
You might like
PHP添加Xdebug扩展的方法
2014/02/12 PHP
THINKPHP支持YAML配置文件的设置方法
2015/03/17 PHP
PHP实现自动识别原编码并对字符串进行编码转换的方法
2016/07/13 PHP
PHP基于DateTime类解决Unix时间戳与日期互转问题【针对1970年前及2038年后时间戳】
2018/06/13 PHP
ASP.NET jQuery 实例18 通过使用jQuery validation插件校验DropDownList
2012/02/03 Javascript
jquery 单引号和双引号的区别及使用注意
2013/07/31 Javascript
jQuery中Ajax的load方法详解
2015/01/14 Javascript
javascript bom是什么及bom和dom的区别
2015/11/26 Javascript
jQuery技巧之让任何组件都支持类似DOM的事件管理
2016/04/05 Javascript
Google 地图事件实例讲解
2016/08/06 Javascript
微信小程序 input输入框控件详解及实例(多种示例)
2016/12/14 Javascript
JS代码实现电脑配置检测功能
2018/03/21 Javascript
vue+axios实现post文件下载
2019/09/25 Javascript
解决vue的router组件component在import时不能使用变量问题
2020/07/26 Javascript
详解JavaScript 的执行机制
2020/09/18 Javascript
ansible作为python模块库使用的方法实例
2017/01/17 Python
python2.7 mayavi 安装图文教程(推荐)
2017/06/22 Python
python中import reload __import__的区别详解
2017/10/16 Python
python中的变量如何开辟内存
2018/06/26 Python
解决Django 在ForeignKey中出现 non-nullable field错误的问题
2019/08/06 Python
分享8点超级有用的Python编程建议(推荐)
2019/10/13 Python
Python assert关键字原理及实例解析
2019/12/13 Python
python读取Kafka实例
2019/12/23 Python
TensorFlow2.X使用图片制作简单的数据集训练模型
2020/04/08 Python
html5 canvas合成海报所遇问题及解决方案总结
2017/08/03 HTML / CSS
城野医生官方海外旗舰店:风靡亚洲毛孔收敛水
2018/04/26 全球购物
党员创先争优公开承诺书
2014/03/28 职场文书
《金色的脚印》教后反思
2014/04/23 职场文书
原料仓仓管员岗位职责
2014/07/08 职场文书
物流专业专科生职业生涯规划书
2014/09/14 职场文书
2015年财务试用期工作总结
2014/12/24 职场文书
世界地球日活动总结
2015/02/09 职场文书
导游词之杭州岳王庙
2019/11/13 职场文书
Python进阶学习之带你探寻Python类的鼻祖-元类
2021/05/08 Python
详解Alibaba Java诊断工具Arthas查看Dubbo动态代理类
2022/04/08 Java/Android
Redis批量生成数据的实现
2022/06/05 Redis