搜尋
首頁後端開發php教程PHP从写简单模板引擎,供新手学习

PHP自写简单模板引擎,供新手学习

今天要写点小东西,突然想到要用模板引擎。就“随手”写了一个,发上来供新手学习。搞了这么久PHP,想想也真是感慨,当年研究了几天的东西现在一两个小时就弄完了,当年一起完耍的女神现在已经不知所踪了。。。咳咳,下面是代码:

<?php /****************&#160;* @author: 一曲忧伤&#160;* @email: [email&#160;protected]&#160;* @discription: 简单模板引擎&#160;*/define(&#39;INVIEW&#39;, true);class view {&#160; &#160; var $tpl_dir = &#39;template&#39;;&#160; &#160; var $cache_dir = &#39;cache&#39;;&#160; &#160; var $tpl_ext = &#39;.html&#39;;&#160; &#160; var $var_left = &#39;{&#39;;&#160; &#160; var $var_right = &#39;}&#39;;&#160; &#160; function __construct($config=array()) {&#160; &#160; &#160; &#160; extract($config);&#160; &#160; &#160; &#160; if(isset($tpl_dir))$this->tpl_dir = $tpl_dir;        if(isset($cache_dir))$this->cache_dir = $cache_dir;        if(isset($tpl_ext))$this->tpl_ext = $tpl_ext;        if(isset($var_left))$this->var_left = $var_left;        if(isset($var_right))$this->var_right = $var_right;    }        function load($tplfilename) {        $tplfile = $this->tpl_dir.'/'.$tplfilename.$this->tpl_ext;        if(!file_exists($tplfile))            die('Template not found: '.$tplfile);        return $this->cache($tplfilename, $tplfile);    }    //判断模板是否缓存,如模板文件有更改则重新编译    function cache($tplname, $tpl_file) {        $cache_file = $this->cache_dir.'/'.md5($tplname).'.php';        if(!file_exists($cache_file) || filemtime($tpl_file)>filemtime($cache_file))            $this->compile($tpl_file, $cache_file);        return $cache_file;    }    //编译模板内容到PHP格式,并写入缓存    function compile($tpl, $cache) {        $body = file_get_contents($tpl);        $vl = $this->var_left;        $vr = $this->var_right;        $patterns = array(            "#$vl\s*include:(.+?)\s*$vr#i",            "#$vl\s*if\s+(.+?)\s*$vr#i",            "#$vl\s*else\s*$vr#i",            "#$vl\s*elseif\s+(.+?)\s*$vr#i",            "#$vl\s*endif\s*$vr#i",            "#$vl\s*/if\s*$vr#i",            "#$vl\s*foreach\s+(.+?):(.+?)\s*$vr#i",            "#$vl\s*endforeach\s*$vr#i",            "#$vl\s*/foreach\s*$vr#i",            "#$vl([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)$vr#i",            "#$vl([0-9a-zA-Z_]+?)\.([0-9a-zA-Z_]+?)$vr#i",            "#$vl([0-9a-zA-Z_\[\]\'\"]+?)$vr#i",            "#$vl([0-9a-zA-Z_]+?):(.*?)$vr#i"        );        $replacements = array(            "<?php include show(&#39;\\1&#39;); ?>",            "<?php if(\\1): ?>",            "<?php else: ?>",            "<?php elseif(\\1): ?>",            "<?php endif; ?>",            "<?php endif; ?>",            "<?php if(count($\\1)>0):\$autoindex=0;foreach($\\1 as \\2):\$autoindex++; ?>",            "<?php endforeach;endif; ?>",            "<?php endforeach;endif; ?>",            "<?php echo $\\1[&#39;\\2&#39;][&#39;\\3&#39;]; ?>",            "<?php echo $\\1[&#39;\\2&#39;]; ?>",            "<?php echo $\\1; ?>",            "<?php echo \\1(\\2); ?>"        );        $body = preg_replace($patterns, $replacements, $body);        file_put_contents($cache, "<?php if(!defined(&#39;INVIEW&#39;))die(&#39;YIQU&#39;); ?>".$body);    }}$view = new view();function show($tpl) {    global $view;    return $view->load($tpl);}

使用方法PHP文件:

<?phpinclude &#39;view.php&#39;;$title = &#39;文档标题&#39;;$a=array(&#39;a&#39;=>'rows','b'=>array('c'=>'inarray')); include show('index');

使用方法HTML模板文件:

<title>{title}</title><meta http-equiv="Content-Type" content="text/html;charset=utf-8">你好,仅供参考<br>{a.a}{a.b.c}<br>{foreach a:$v}{autoindex}.{v}<br>{/foreach}{include:footer}

模板文件放在template目录,缓存放在cahce目录,这两个目录都要手动创建,缓存加上判断不可直接访问。可以使用

{include:子模板}

{if 条件}

{foreach 变量:as语句},$autoindex为自增变量

{调用函数:参数}

{变量},包含数组变量简化写法(最多只支持三维数组)

等语法。

好了,整个模板引擎实现比较简单,因为一直比较喜欢这种include方式的模板,只供新手学习原理就好了。


=====================国际惯例=======================

刚开始学着写一些博客,写得不好的地方请见谅,觉得还可以就赏脸赞下吧!

我的QQ群(PHP)336533596,QQ 451309839,欢迎加入。相互交流,聊天吹牛~


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何使PHP應用程序更快如何使PHP應用程序更快May 12, 2025 am 12:12 AM

tomakephpapplicationsfaster,關注台詞:1)useopcodeCachingLikeLikeLikeLikeLikePachetoStorePreciledScompiledScriptbyTecode.2)MinimimiedAtabaseSqueriSegrieSqueriSegeriSybysequeryCachingandeffeftExting.3)Leveragephp7 leveragephp7 leveragephp7 leveragephpphp7功能forbettercodeefficy.4)

PHP性能優化清單:立即提高速度PHP性能優化清單:立即提高速度May 12, 2025 am 12:07 AM

到ImprovephPapplicationspeed,關注台詞:1)啟用opcodeCachingwithapCutoredUcescriptexecutiontime.2)實現databasequerycachingingusingpdotominiminimizedatabasehits.3)usehttp/2tomultiplexrequlexrequestsandreduceconnection.4 limitesclection.4.4

PHP依賴注入:提高代碼可檢驗性PHP依賴注入:提高代碼可檢驗性May 12, 2025 am 12:03 AM

依赖注入(DI)通过显式传递依赖关系,显著提升了PHP代码的可测试性。1)DI解耦类与具体实现,使测试和维护更灵活。2)三种类型中,构造函数注入明确表达依赖,保持状态一致。3)使用DI容器管理复杂依赖,提升代码质量和开发效率。

PHP性能優化:數據庫查詢優化PHP性能優化:數據庫查詢優化May 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

簡單指南:帶有PHP腳本的電子郵件發送簡單指南:帶有PHP腳本的電子郵件發送May 12, 2025 am 12:02 AM

phpisusedforsenderemailsduetoitsbuilt-inmail()函數andsupportivelibrariesLikePhpMailerAndSwiftMailer.1)usethemail()functionForbasiceMails,butithasimails.2)butithasimail.2)

PHP性能:識別和修復瓶頸PHP性能:識別和修復瓶頸May 11, 2025 am 12:13 AM

PHP性能瓶颈可以通过以下步骤解决:1)使用Xdebug或Blackfire进行性能分析,找出问题所在;2)优化数据库查询并使用缓存,如APCu;3)使用array_filter等高效函数优化数组操作;4)配置OPcache进行字节码缓存;5)优化前端,如减少HTTP请求和优化图片;6)持续监控和优化性能。通过这些方法,可以显著提升PHP应用的性能。

PHP的依賴注入:快速摘要PHP的依賴注入:快速摘要May 11, 2025 am 12:09 AM

依賴性注射(DI)InphpisadesignPatternthatManages和ReducesClassDeptions,增強量強制性,可驗證性和MATIALWINABIOS.ItallowSpasspassingDepentenciesLikEdenciesLikedAbaseConnectionStoclasseconnectionStoclasseSasasasasareTers,interitationAseTestingEaseTestingEaseTestingEaseTestingEasingAndScalability。

提高PHP性能:緩存策略和技術提高PHP性能:緩存策略和技術May 11, 2025 am 12:08 AM

cachingimprovesphpermenceByStorcyResultSofComputationsorqucrouctationsorquctationsorquickretrieval,reducingServerLoadAndenHancingResponsetimes.feftectivestrategiesinclude:1)opcodecaching,whereStoresCompiledSinmememorytssinmemorytoskipcompliation; 2)datacaching datacachingsingMemccachingmcachingmcachings

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)