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


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 相关文章推荐
PHP4实际应用经验篇(4)
Oct 09 PHP
MySQL GBK→UTF-8编码转换
May 24 PHP
php 获取select下拉列表框的值
May 08 PHP
基于PHP 面向对象之成员方法详解
May 04 PHP
PHP开发工具ZendStudio下Xdebug工具使用说明详解
Nov 11 PHP
ThinkPHP3.1新特性之多数据库操作更加完善
Jun 19 PHP
主流PHP框架的优缺点对比分析
Dec 25 PHP
PHP、Java des加密解密实例
Apr 27 PHP
WordPress中给媒体文件添加分类和标签的PHP功能实现
Dec 31 PHP
Zend Framework教程之Zend_Db_Table表关联实例详解
Mar 23 PHP
php将一维数组转换为每3个连续值组成的二维数组
May 06 PHP
php中引用符号(&amp;)的使用详细介绍
Dec 06 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 定界符格式引起的错误
2011/05/24 PHP
10个实用的PHP代码片段
2011/09/02 PHP
Yii统计不同类型邮箱数量的方法
2016/10/18 PHP
PHP实现移除数组中为空或为某值元素的方法
2017/01/07 PHP
phpcms实现验证码替换及phpcms实现全站搜索功能教程详解
2017/12/13 PHP
php使用socket调用http和smtp协议实例小结
2019/07/26 PHP
浅谈JavaScript 中有关时间对象的方法
2016/08/15 Javascript
深入理解vue Render函数
2017/07/19 Javascript
jQuery实现锚点向下平滑滚动特效示例
2017/08/29 jQuery
React+Antd+Redux实现待办事件的方法
2019/03/14 Javascript
js实现固定区域内的不重叠随机圆
2019/10/24 Javascript
springboot+vue+对接支付宝接口+二维码扫描支付功能(沙箱环境)
2020/10/15 Javascript
微信小程序学习之自定义滚动弹窗
2020/12/20 Javascript
[29:23]2014 DOTA2国际邀请赛中国区预选赛 LGD-GAMING VS CIS 第一场1
2014/05/23 DOTA
Python字符转换
2008/09/06 Python
Python中os.path用法分析
2015/01/15 Python
Python中使用PIPE操作Linux管道
2015/02/04 Python
实用自动化运维Python脚本分享
2018/06/04 Python
Python判断中文字符串是否相等的实例
2018/07/06 Python
Python requests库用法实例详解
2018/08/14 Python
使用Python和Prometheus跟踪天气的使用方法
2019/05/06 Python
为什么你还不懂得怎么使用Python协程
2019/05/13 Python
TensorFlow 显存使用机制详解
2020/02/03 Python
Python图像处理库PIL的ImageDraw模块介绍详解
2020/02/26 Python
Python进行特征提取的示例代码
2020/10/15 Python
Django多数据库联用实现方法解析
2020/11/12 Python
CSS3 Media Queries详细介绍和使用实例
2014/05/08 HTML / CSS
YOOX美国官方网站:全球著名的多品牌时尚网络概念店
2016/09/11 全球购物
美国受欢迎的女性牛仔裤品牌:DL1961
2016/11/12 全球购物
我的applet原先好好的, 一放到web server就会有问题,为什么?
2016/05/10 面试题
2014年开学第一课活动方案
2014/03/06 职场文书
基层干部个人对照检查及整改措施
2014/10/28 职场文书
先进工作者主要事迹材料
2015/11/03 职场文书
Django如何与Ajax交互
2021/04/29 Python
html form表单基础入门案例讲解
2021/07/15 HTML / CSS
Mysql事务索引知识汇总
2022/03/17 MySQL