<p id="xpasp"><font id="xpasp"></font></p>

<track id="xpasp"><th id="xpasp"></th></track>
  • <menu id="xpasp"></menu>
  • \n{include \"test.php\"}\n\n{#}這是一條PHP的注釋,在HTML頁(yè)面里是不顯示的,只會(huì)在生成的編譯文件里顯示{#}\n我將被index.php導(dǎo)入\n{$name}這個(gè)標(biāo)簽必須經(jīng)過(guò)Parser.class.php這個(gè)解析類來(lái)解析它1\n
    \n這里的內(nèi)容改變了,為什么?\n
    \n{if $a}\n顯示一號(hào)皮膚\n{else}\n顯示二號(hào)皮膚\n{\/if}\n
    \n{foreach $array(key,value)}\n{@key}....{@value}
    \n{\/foreach}\n<\/body>\n<\/html>\n<\/pre>\n\n

      <\/p>\n

    模板類:<\/p>\n\n

             \/\/Templates.class.php   \n\tclass Templates {\n\t    \/\/創(chuàng)建一個(gè)存放數(shù)組的字段\n\t    private $_vars = array();\n\t    private $_config = array();\n\t    \/\/創(chuàng)建一個(gè)構(gòu)造方法\n\t    public function __construct(){\n\t        if(!is_dir(TPL_DIR) || !is_dir(TPL_C_DIR) || !is_dir(CACHE_DIR) ){\n\t            exit('ERROR:模板文件夾或者編譯文件夾或者緩存文件夾沒(méi)有創(chuàng)建!');\n\t        }\n\t        \/\/獲取系統(tǒng)變量\n\t        $_sxe = simplexml_load_file(ROOT_PATH.'\/config\/profile.xml');\n\t        $_taglib = $_sxe->xpath('\/root\/taglib');\n\t        foreach($_taglib as $_tag){\n\t            $this->_config[\"$_tag->name\"] = $_tag->value;\n\t        }\n\t    }\n\t  \n\t    \n\t    \/\/創(chuàng)建變量注入方法\n\t    \/**\n\t     * assign()變量注入方法\n\t     * @param  $_var 要注入的變量名,對(duì)應(yīng).tpl文件中的需要替換的變量 \n\t     * @param  $_values 要注入的變量值\n\t     *\/\n\t    public function assign($_var,$_values){\n\t        if(isset($_var) && !empty($_var)){\n\t            $this->_vars[$_var] = $_values;\n\t            \n\t        }else{\n\t            exit('ERROR:請(qǐng)?jiān)O(shè)置變量名!');\n\t        }\n\t        \n\t    }\n\t    \n\t    \n\t    \/\/創(chuàng)建一個(gè)顯示方法,用來(lái)顯示編譯后的文件\n\t    public function display($_file){\n\t        \/\/設(shè)置模板文件的路徑\n\t        $_tplFile = TPL_DIR.$_file;\n\t        \/\/判斷模板文件是否存在\n\t        if(!file_exists($_tplFile)){\n\t            exit('ERROR:模板文件不存在');\n\t        }\n\t        \/\/設(shè)置編譯文件名\n\t        $_parFile  = TPL_C_DIR.md5($_file).$_file.'.php';\n\t        \/\/設(shè)置緩存文件名\n\t        $_cacheFile = CACHE_DIR.md5($_file).$_file.'.html';\n\t        \/\/判斷緩存狀態(tài)\n\t        if(IS_CACHE){\n\t            \/\/判斷緩存文件是否存在\n\t            if(file_exists($_cacheFile) && file_exists($_parFile)){\n\t                \/\/是否修改過(guò)編譯文件或者模板文件\n\t                if(filemtime($_cacheFile)>=filemtime($_parFile) && filemtime($_parFile)>filemtime($_tplFile)){\n\t                    echo '以下是緩存文件內(nèi)容';\n\t                    echo \"
    \";\n\t include $_cacheFile;\n\t return;\n\t }\n\t }\n\t }\n\t \/\/判斷編譯文件是否存在,模板文件是否修改過(guò)\n\t if(!file_exists($_parFile) || (filemtime($_parFile) < filemtime($_tplFile))){\n\t \n\t \/\/引入模板解析類\n\t require ROOT_PATH.'\/includes\/Parser.class.php';\n\t \/\/實(shí)例化對(duì)象,生成編譯文件\n\t $_parser = new Parser($_tplFile);\/\/模板文件\n\t $_parser->compile($_parFile);\/\/編譯后文件\n\t \n\t }\n\n\t \/\/載入編譯文件\n\t include $_parFile;\n\t if(IS_CACHE){\n \t \/\/生成緩存文件\n \t file_put_contents($_cacheFile, ob_get_contents());\n \t \/\/清除緩沖區(qū)\n \t ob_end_clean();\n \t \/\/載入緩存文件\n \t include $_cacheFile;\n\t }\n\n\n\t }\n\t}\n<\/pre>\n\n

    解析類:<\/p>\n\n

    \/\/Parser.class.php\n\tclass Parser {\n\t    \/\/獲取模板內(nèi)容\n\t    private $_tpl;\n\t    \/\/構(gòu)造方法,初始化模板\n\t    public function __construct($_tplFile){\n\t        \/\/判斷文件是否存在\n\t        if(!$this->_tpl = file_get_contents($_tplFile)){\n\t            exit('ERROR:讀取模板出錯(cuò)!');\n\t        }\n\t        \n\t    }\n\t    \n\t    \/\/解析普通變量\n\t    private function parVar(){\n    \t    $_pattern = '\/\\{\\$([\\w]+)\\}\/';\n    \t\tif (preg_match($_pattern,$this->_tpl)) {\n    \t\t\t$this->_tpl = preg_replace($_pattern,\"_vars['$1'] ?>\",$this->_tpl);\n    \t\t}\n\t    }\n\t    \/\/解析IF條件語(yǔ)句\n\t    private function parIf(){\n\t        \/\/開(kāi)頭if模式\n\t        $_patternIf = '\/\\{if\\s+\\$([\\w]+)\\}\/';\n\t        \/\/結(jié)尾if模式\n\t        $_patternEnd = '\/\\{\\\/if\\}\/';\n\t        \/\/else模式\n\t        $_patternElse = '\/\\{else\\}\/';\n\t        \/\/判斷if是否存在\n\t        if(preg_match($_patternIf, $this->_tpl)){\n\t            \/\/判斷是否有if結(jié)尾\n\t            if(preg_match($_patternEnd, $this->_tpl)){\n\t                \/\/替換開(kāi)頭IF\n\t                $this->_tpl = preg_replace($_patternIf, \"_vars['$1']){ ?>\", $this->_tpl);\n\t                \/\/替換結(jié)尾IF\n\t                $this->_tpl = preg_replace($_patternEnd, \"\", $this->_tpl);\n\t                \/\/判斷是否有else\n\t                if(preg_match($_patternElse, $this->_tpl)){\n\t                    \/\/替換else\n\t                    $this->_tpl = preg_replace($_patternElse, \"\", $this->_tpl);\n\t                }\n\t            }else{\n\t                exit('ERROR:語(yǔ)句沒(méi)有關(guān)閉!');\n\t            }\n\t        }\n\t    }\n\t    \/\/解析foreach\n\t    private function parForeach(){\n\t        $_patternForeach = '\/\\{foreach\\s+\\$(\\w+)\\((\\w+),(\\w+)\\)\\}\/';\n\t        $_patternEndForeach = '\/\\{\\\/foreach\\}\/';\n\t        \/\/foreach里的值\n\t        $_patternVar = '\/\\{@(\\w+)\\}\/';\n\t        \/\/判斷是否存在\n\t        if(preg_match($_patternForeach, $this->_tpl)){\n\t            \/\/判斷結(jié)束標(biāo)志\n\t            if(preg_match($_patternEndForeach, $this->_tpl)){\n\t                \/\/替換開(kāi)頭\n\t                $this->_tpl = preg_replace($_patternForeach, \"_vars['$1'] as \\$$2=>\\$$3){?>\", $this->_tpl);\n\t                \/\/替換結(jié)束\n\t                $this->_tpl = preg_replace($_patternEndForeach, \"\", $this->_tpl);\n\t                \/\/替換值\n\t                $this->_tpl = preg_replace($_patternVar, \"\", $this->_tpl);\n\t            }else{\n\t                exit('ERROR:Foreach語(yǔ)句沒(méi)有關(guān)閉');\n\t            }\n\t        }\n\t    }\n\t    \/\/解析include\n\t    private function parInclude(){\n\t        $_pattern = '\/\\{include\\s+\\\"(.*)\\\"\\}\/';\n\t        if(preg_match($_pattern, $this->_tpl,$_file)){\n\t            \/\/判斷頭文件是否存在\n\t            if(!file_exists($_file[1]) || empty($_file[1])){\n\t                exit('ERROR:包含文件不存在!');\n\t            }\n                \/\/替換內(nèi)容\n                $this->_tpl = preg_replace($_pattern, \"\", $this->_tpl);\n\t        }\n\t    }\n\t    \/\/解析系統(tǒng)變量\n\t    private function configVar(){\n\t        $_pattern = '\/\/';\n\t        if(preg_match($_pattern, $this->_tpl,$_file)){\n \t            $this->_tpl = preg_replace($_pattern,\"_config['$1'] ?>\", $this->_tpl);\n                \n\t        }\n\t    }\n\t    \n\t    \/\/解析單行PHP注釋\n\t    private function parCommon(){\n\t        $_pattern = '\/\\{#\\}(.*)\\{#\\}\/';\n\t        if(preg_match($_pattern, $this->_tpl)){\n\t            $this->_tpl = preg_replace($_pattern, \"\", $this->_tpl);\n\t        }\n\t    }\n\t    \n\t    \n\t    \/\/生成編譯文件\n\t    public function compile($_parFile){\n\t        \/\/解析模板變量\n\t        $this->parVar();\n\t        \/\/解析IF\n\t        $this->parIf();\n\t        \/\/解析注釋\n\t        $this->parCommon();\n\t        \/\/解析Foreach\n\t        $this->parForeach();\n\t        \/\/解析include\n\t        $this->parInclude();\n\t        \/\/解析系統(tǒng)變量\n\t        $this->configVar();\n\t        \/\/生成編譯文件\n\t        if(!file_put_contents($_parFile, $this->_tpl)){\n\t            exit('ERROR:編譯文件生成失?。?);\n\t        }\n\t    }\n\t}\n<\/pre>\n\n

      <\/p>\n

    總結(jié):模板引擎的整個(gè)過(guò)程:<\/p>\n

      1、當(dāng)瀏覽器請(qǐng)求index.php文件時(shí),實(shí)例化模板類對(duì)像?$_tpl = new Templates();<\/p>\n

      2、當(dāng)Templates實(shí)例化的時(shí)候,生成兩個(gè)數(shù)組,一個(gè)用來(lái)存放模板變量,另一個(gè)存放系統(tǒng)變量,通過(guò)構(gòu)造方法,判斷文件夾是否存在,同時(shí)通過(guò)XML文件將系統(tǒng)變量數(shù)組初始化<\/p>\n

      3、通過(guò)模板類Templates的注入方法,assign(),將對(duì)應(yīng)模板index.tpl中變量的index.php的內(nèi)容注入到模板類的私有變量,完成初始化<\/p>\n

      4、模板類Templates類顯示方法display() 通過(guò)實(shí)例化解析類Parser,將取到的注入變量通過(guò)解析類進(jìn)行解析(即替換)<\/p>\n

      5、解析(替換)后,將文件寫入PHP、HTML混全文件<\/p>\n

      6、通過(guò)Templates類的顯示方法將文件輸出:<\/p>\n

         1、第一次執(zhí)行顯示方法時(shí),將會(huì)把PHP、HTML混合文件,生成純靜態(tài)的緩存文件<\/p>\n

         2、調(diào)用緩存文件,顯示頁(yè)面<\/p>\n

      <\/span>  <\/span> 3、當(dāng)瀏覽器再次調(diào)用顯示方法時(shí),首先根據(jù)各文件的最后修改時(shí)間,判斷是否重新生成緩存文件或直接調(diào)用已存在的緩存文件<\/span><\/p>\n

    重點(diǎn):<\/span><\/p>\n

      1、通過(guò)正則表達(dá)式進(jìn)行字符串的替換<\/span><\/p>\n

      2、熟悉OOP<\/span><\/p>\n

      <\/p>\n

    ?<\/p>\n

    <\/p>\n

    \nhttp:\/\/www.bkjia.com\/PHPjc\/1055139.html<\/span>www.bkjia.com<\/span>true<\/span>http:\/\/www.bkjia.com\/PHPjc\/1055139.html<\/span>TechArticle<\/span>PHP--關(guān)于模板的原理和解析,php--模板解析 此內(nèi)容用作筆記,以備日后查看,此內(nèi)容為學(xué)習(xí)李炎恢課程而來(lái),并非自己所創(chuàng),如有問(wèn)題請(qǐng)...<\/span>\n<\/div>\n
    <\/div>\n"}

    国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

    Table of Contents
    PHP--關(guān)于模板的原理和解析,php--模板解析
    Home Backend Development PHP Tutorial PHP--About the principles and analysis of templates, php--Template analysis_PHP tutorial

    PHP--About the principles and analysis of templates, php--Template analysis_PHP tutorial

    Jul 12, 2016 am 09:08 AM
    template engine

    PHP--關(guān)于模板的原理和解析,php--模板解析

    此內(nèi)容用作筆記,以備日后查看,此內(nèi)容為學(xué)習(xí)李炎恢課程而來(lái),并非自己所創(chuàng),如有問(wèn)題請(qǐng)私信~

    將PHP代碼和靜態(tài)HTML代碼進(jìn)行分離,使代碼的可讀性和維護(hù)性得到顯著提高。

    使用模板引擎:

    ? ? 我們所說(shuō)的模板是Web模板,是主要由HTML標(biāo)記組成的語(yǔ)言來(lái)編寫的頁(yè)面,但也有如何表示包含動(dòng)態(tài)生成內(nèi)容的方式(解析標(biāo)簽)。模板引擎是一種軟件庫(kù),允許我們從模板生成HTML代碼,并指定要包含的動(dòng)態(tài)內(nèi)容。

      模板引擎的特點(diǎn):

      1.鼓勵(lì)分離:讓更個(gè)系統(tǒng)的可讀性和維護(hù)性得到提高。
      2.促進(jìn)分工:使得程序員和美工去專心處理自己的設(shè)計(jì)。
      3.比PHP更容易解析:編譯文件和緩存文件加載更快、占資源更少。
      4.增加安全性:可限制模板設(shè)計(jì)師進(jìn)行不安全的操作的能力避免誤刪誤訪問(wèn)等。

    模板處理的流程圖

      

    ?

    創(chuàng)建模板:

      1、創(chuàng)建初始模板所需要的文件夾和文件。

      a) index.php主文件,用于編寫業(yè)務(wù)邏輯。
      b) template.inc.php模板初始化文件,用于初始模版信息。
      c) templates目錄存放所有的模板文件。
      d) templates_c目錄存放所有編譯文件。
      e) cache目錄存放所有緩存文件。
      f) includes目錄存放所有的類文件。
      g) config目錄存放模板系統(tǒng)變量配置文件。

      

      以下是源碼:

    主文件 index.php  

    <?<span>php
       //index.php</span>

      //設(shè)置編碼為UTF-8
      header('Content-Type:text/html;Charset=utf-8');
      //網(wǎng)站根目錄
      define('ROOT_PATH', dirname(__FILE__));
      //存放模板文件夾
      define('TPL_DIR', ROOT_PATH.'/templates/');
      //編譯文件夾
      define('TPL_C_DIR', ROOT_PATH.'/templates_c/');
      //緩存文件夾
      define('CACHE_DIR', ROOT_PATH.'/cache/');
      //定義緩存狀態(tài)
      define('IS_CACHE',true);
      //設(shè)置緩存狀態(tài)開(kāi)關(guān)
      IS_CACHE ? ob_start() : null;

      include ROOT_PATH.'/includes/Templates.class.php';

    <span>  </span><span>$_name</span> = '方塊李'<span>;
        
        </span><span>$array</span> = <span>array</span>(1,2,3,4,5,6<span>);
        </span><span>$_tpl</span> = <span>new</span><span> Templates();
        </span><span>$_tpl</span>->assign('name', <span>$_name</span><span>);
        </span><span>$_tpl</span>->assign('a', 5>4<span>);
        </span><span>$_tpl</span>->assign('array', <span>$array</span><span>);
        </span><span>//</span><span>顯示</span>
        <span>$_tpl</span>->display('index.tpl'<span>);
    </span>?>

    模板文件 HTML

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title><!--{webname}--></title>
    
    </head>
    <body>
    {include "test.php"}
    <!-- 這是HTML的注釋 -->
    {#}這是一條PHP的注釋,在HTML頁(yè)面里是不顯示的,只會(huì)在生成的編譯文件里顯示{#}
    我將被index.php導(dǎo)入
    {$name}這個(gè)標(biāo)簽必須經(jīng)過(guò)Parser.class.php這個(gè)解析類來(lái)解析它1
    <br />
    這里的內(nèi)容改變了,為什么?
    <br />
    {if $a}
    顯示一號(hào)皮膚
    {else}
    顯示二號(hào)皮膚
    {/if}
    <br />
    {foreach $array(key,value)}
    {@key}....{@value} <br />
    {/foreach}
    </body>
    </html>
    

      

    模板類:

             //Templates.class.php   
    	class Templates {
    	    //創(chuàng)建一個(gè)存放數(shù)組的字段
    	    private $_vars = array();
    	    private $_config = array();
    	    //創(chuàng)建一個(gè)構(gòu)造方法
    	    public function __construct(){
    	        if(!is_dir(TPL_DIR) || !is_dir(TPL_C_DIR) || !is_dir(CACHE_DIR) ){
    	            exit('ERROR:模板文件夾或者編譯文件夾或者緩存文件夾沒(méi)有創(chuàng)建!');
    	        }
    	        //獲取系統(tǒng)變量
    	        $_sxe = simplexml_load_file(ROOT_PATH.'/config/profile.xml');
    	        $_taglib = $_sxe->xpath('/root/taglib');
    	        foreach($_taglib as $_tag){
    	            $this->_config["$_tag->name"] = $_tag->value;
    	        }
    	    }
    	  
    	    
    	    //創(chuàng)建變量注入方法
    	    /**
    	     * assign()變量注入方法
    	     * @param  $_var 要注入的變量名,對(duì)應(yīng).tpl文件中的需要替換的變量 
    	     * @param  $_values 要注入的變量值
    	     */
    	    public function assign($_var,$_values){
    	        if(isset($_var) && !empty($_var)){
    	            $this->_vars[$_var] = $_values;
    	            
    	        }else{
    	            exit('ERROR:請(qǐng)?jiān)O(shè)置變量名!');
    	        }
    	        
    	    }
    	    
    	    
    	    //創(chuàng)建一個(gè)顯示方法,用來(lái)顯示編譯后的文件
    	    public function display($_file){
    	        //設(shè)置模板文件的路徑
    	        $_tplFile = TPL_DIR.$_file;
    	        //判斷模板文件是否存在
    	        if(!file_exists($_tplFile)){
    	            exit('ERROR:模板文件不存在');
    	        }
    	        //設(shè)置編譯文件名
    	        $_parFile  = TPL_C_DIR.md5($_file).$_file.'.php';
    	        //設(shè)置緩存文件名
    	        $_cacheFile = CACHE_DIR.md5($_file).$_file.'.html';
    	        //判斷緩存狀態(tài)
    	        if(IS_CACHE){
    	            //判斷緩存文件是否存在
    	            if(file_exists($_cacheFile) && file_exists($_parFile)){
    	                //是否修改過(guò)編譯文件或者模板文件
    	                if(filemtime($_cacheFile)>=filemtime($_parFile) && filemtime($_parFile)>filemtime($_tplFile)){
    	                    echo '以下是緩存文件內(nèi)容';
    	                    echo "<br />";
    	                    include $_cacheFile;
    	                    return;
    	                }
    	            }
    	        }
    	        //判斷編譯文件是否存在,模板文件是否修改過(guò)
    	        if(!file_exists($_parFile) || (filemtime($_parFile) < filemtime($_tplFile))){
    	            
    	            //引入模板解析類
    	            require ROOT_PATH.'/includes/Parser.class.php';
    	            //實(shí)例化對(duì)象,生成編譯文件
    	            $_parser = new Parser($_tplFile);//模板文件
    	            $_parser->compile($_parFile);//編譯后文件
    	            
    	        }
    
    	        //載入編譯文件
    	        include $_parFile;
    	        if(IS_CACHE){
        	        //生成緩存文件
        	        file_put_contents($_cacheFile, ob_get_contents());
        	        //清除緩沖區(qū)
        	        ob_end_clean();
        	        //載入緩存文件
        	        include $_cacheFile;
    	        }
    
    
    	    }
    	}
    

    解析類:

    //Parser.class.php
    	class Parser {
    	    //獲取模板內(nèi)容
    	    private $_tpl;
    	    //構(gòu)造方法,初始化模板
    	    public function __construct($_tplFile){
    	        //判斷文件是否存在
    	        if(!$this->_tpl = file_get_contents($_tplFile)){
    	            exit('ERROR:讀取模板出錯(cuò)!');
    	        }
    	        
    	    }
    	    
    	    //解析普通變量
    	    private function parVar(){
        	    $_pattern = '/\{\$([\w]+)\}/';
        		if (preg_match($_pattern,$this->_tpl)) {
        			$this->_tpl = preg_replace($_pattern,"<?php echo \$this->_vars['$1'] ?>",$this->_tpl);
        		}
    	    }
    	    //解析IF條件語(yǔ)句
    	    private function parIf(){
    	        //開(kāi)頭if模式
    	        $_patternIf = '/\{if\s+\$([\w]+)\}/';
    	        //結(jié)尾if模式
    	        $_patternEnd = '/\{\/if\}/';
    	        //else模式
    	        $_patternElse = '/\{else\}/';
    	        //判斷if是否存在
    	        if(preg_match($_patternIf, $this->_tpl)){
    	            //判斷是否有if結(jié)尾
    	            if(preg_match($_patternEnd, $this->_tpl)){
    	                //替換開(kāi)頭IF
    	                $this->_tpl = preg_replace($_patternIf, "<?php if(\$this->_vars['$1']){ ?>", $this->_tpl);
    	                //替換結(jié)尾IF
    	                $this->_tpl = preg_replace($_patternEnd, "<?php } ?>", $this->_tpl);
    	                //判斷是否有else
    	                if(preg_match($_patternElse, $this->_tpl)){
    	                    //替換else
    	                    $this->_tpl = preg_replace($_patternElse, "<?php }else{ ?>", $this->_tpl);
    	                }
    	            }else{
    	                exit('ERROR:語(yǔ)句沒(méi)有關(guān)閉!');
    	            }
    	        }
    	    }
    	    //解析foreach
    	    private function parForeach(){
    	        $_patternForeach = '/\{foreach\s+\$(\w+)\((\w+),(\w+)\)\}/';
    	        $_patternEndForeach = '/\{\/foreach\}/';
    	        //foreach里的值
    	        $_patternVar = '/\{@(\w+)\}/';
    	        //判斷是否存在
    	        if(preg_match($_patternForeach, $this->_tpl)){
    	            //判斷結(jié)束標(biāo)志
    	            if(preg_match($_patternEndForeach, $this->_tpl)){
    	                //替換開(kāi)頭
    	                $this->_tpl = preg_replace($_patternForeach, "<?php foreach(\$this->_vars['$1'] as \$$2=>\$$3){?>", $this->_tpl);
    	                //替換結(jié)束
    	                $this->_tpl = preg_replace($_patternEndForeach, "<?php } ?>", $this->_tpl);
    	                //替換值
    	                $this->_tpl = preg_replace($_patternVar, "<?php echo \$$1?>", $this->_tpl);
    	            }else{
    	                exit('ERROR:Foreach語(yǔ)句沒(méi)有關(guān)閉');
    	            }
    	        }
    	    }
    	    //解析include
    	    private function parInclude(){
    	        $_pattern = '/\{include\s+\"(.*)\"\}/';
    	        if(preg_match($_pattern, $this->_tpl,$_file)){
    	            //判斷頭文件是否存在
    	            if(!file_exists($_file[1]) || empty($_file[1])){
    	                exit('ERROR:包含文件不存在!');
    	            }
                    //替換內(nèi)容
                    $this->_tpl = preg_replace($_pattern, "<?php include '$1';?>", $this->_tpl);
    	        }
    	    }
    	    //解析系統(tǒng)變量
    	    private function configVar(){
    	        $_pattern = '/<!--\{(\w+)\}-->/';
    	        if(preg_match($_pattern, $this->_tpl,$_file)){
     	            $this->_tpl = preg_replace($_pattern,"<?php echo \$this->_config['$1'] ?>", $this->_tpl);
                    
    	        }
    	    }
    	    
    	    //解析單行PHP注釋
    	    private function parCommon(){
    	        $_pattern = '/\{#\}(.*)\{#\}/';
    	        if(preg_match($_pattern, $this->_tpl)){
    	            $this->_tpl = preg_replace($_pattern, "<?php /*($1) */?>", $this->_tpl);
    	        }
    	    }
    	    
    	    
    	    //生成編譯文件
    	    public function compile($_parFile){
    	        //解析模板變量
    	        $this->parVar();
    	        //解析IF
    	        $this->parIf();
    	        //解析注釋
    	        $this->parCommon();
    	        //解析Foreach
    	        $this->parForeach();
    	        //解析include
    	        $this->parInclude();
    	        //解析系統(tǒng)變量
    	        $this->configVar();
    	        //生成編譯文件
    	        if(!file_put_contents($_parFile, $this->_tpl)){
    	            exit('ERROR:編譯文件生成失??!');
    	        }
    	    }
    	}
    

      

    總結(jié):模板引擎的整個(gè)過(guò)程:

      1、當(dāng)瀏覽器請(qǐng)求index.php文件時(shí),實(shí)例化模板類對(duì)像?$_tpl = new Templates();

      2、當(dāng)Templates實(shí)例化的時(shí)候,生成兩個(gè)數(shù)組,一個(gè)用來(lái)存放模板變量,另一個(gè)存放系統(tǒng)變量,通過(guò)構(gòu)造方法,判斷文件夾是否存在,同時(shí)通過(guò)XML文件將系統(tǒng)變量數(shù)組初始化

      3、通過(guò)模板類Templates的注入方法,assign(),將對(duì)應(yīng)模板index.tpl中變量的index.php的內(nèi)容注入到模板類的私有變量,完成初始化

      4、模板類Templates類顯示方法display() 通過(guò)實(shí)例化解析類Parser,將取到的注入變量通過(guò)解析類進(jìn)行解析(即替換)

      5、解析(替換)后,將文件寫入PHP、HTML混全文件

      6、通過(guò)Templates類的顯示方法將文件輸出:

         1、第一次執(zhí)行顯示方法時(shí),將會(huì)把PHP、HTML混合文件,生成純靜態(tài)的緩存文件

         2、調(diào)用緩存文件,顯示頁(yè)面

         3、當(dāng)瀏覽器再次調(diào)用顯示方法時(shí),首先根據(jù)各文件的最后修改時(shí)間,判斷是否重新生成緩存文件或直接調(diào)用已存在的緩存文件

    重點(diǎn):

      1、通過(guò)正則表達(dá)式進(jìn)行字符串的替換

      2、熟悉OOP

      

    ?

    www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1055139.htmlTechArticlePHP--關(guān)于模板的原理和解析,php--模板解析 此內(nèi)容用作筆記,以備日后查看,此內(nèi)容為學(xué)習(xí)李炎恢課程而來(lái),并非自己所創(chuàng),如有問(wèn)題請(qǐng)...
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    ThinkPHP6 template engine usage guide: Create an exquisite front-end interface ThinkPHP6 template engine usage guide: Create an exquisite front-end interface Aug 26, 2023 pm 11:09 PM

    ThinkPHP6 template engine usage guide: Create an exquisite front-end interface Introduction: With the development of web applications, the design and development of front-end interfaces have become increasingly important. As a developer, we need to use a powerful template engine to help us create and manage front-end interfaces. ThinkPHP6's template engine is a powerful tool to meet this need. This article will introduce how to use the ThinkPHP6 template engine to create a beautiful front-end interface. Part 1: Install ThinkPHP6 template engine

    What are the common template engines in PHP programming? What are the common template engines in PHP programming? Jun 12, 2023 am 09:50 AM

    In recent years, the template engine in PHP programming has become an important part of PHP development, making it easier for programmers to develop and manage pages. This article will introduce common template engines in PHP programming. SmartySmarty is a commonly used PHP template engine. It supports a series of functions such as cached templates, plug-in modules and custom functions. Smarty's syntax is very flexible and can solve the problem of combining PHP variables with HTML tags, making the PHP language more suitable for templated design. Moreover, S

    Template engine selection and usage experience sharing in JavaScript development Template engine selection and usage experience sharing in JavaScript development Nov 04, 2023 am 11:42 AM

    Sharing experience on template engine selection and use in JavaScript development Introduction: In modern front-end development, the template engine (TemplateEngine) plays a crucial role. They enable developers to organize and manage large amounts of dynamic data more efficiently and effectively separate data from interface presentation. At the same time, choosing an appropriate template engine can also bring developers a better development experience and performance optimization. However, among the many JavaScript template engines, which one should you choose? catch

    How to use template engine Blade in Fat-Free framework? How to use template engine Blade in Fat-Free framework? Jun 03, 2023 pm 08:40 PM

    Fat-Free Framework is a lightweight PHP framework designed to provide simple and flexible tools for building web applications. It contains many useful features such as routing, database access, caching, etc. In the Fat-Free framework, using the Blade template engine can help us manage and render templates more conveniently. Blade is the template engine in the Laravel framework, which provides powerful syntax and template inheritance capabilities. In this article I will demonstrate how to use Bl in Fat-Free framework

    Learn to use the Golang template engine: A basic guide to using templates in Golang Learn to use the Golang template engine: A basic guide to using templates in Golang Jan 20, 2024 am 10:13 AM

    Golang Template Engine Getting Started Guide: How to use templates in Golang, specific code examples are required Introduction: A template engine is a tool that can combine data and templates and generate documents in HTML, text or other formats. In Golang, we can use the built-in template package (html/template) to implement the functions of the template engine. This article will introduce in detail how to use the template engine in Golang and provide specific code examples. 1. The basic concept of template engine is to understand how to use it.

    Template engines for PHP and CGI: How to achieve website reusability Template engines for PHP and CGI: How to achieve website reusability Jul 20, 2023 pm 10:13 PM

    PHP and CGI template engines: How to achieve website reusability Introduction: When developing websites, we often need to deal with the display of dynamic content. In order to achieve code maintainability and reusability, using a template engine is a wise choice. This article will introduce PHP and CGI, two commonly used template engines, and show how to use them to achieve website reusability through code examples. 1. PHP template engine PHP is a widely used server scripting language with flexibility and powerful functions. PHP template engine is a

    Template Engine in Go: A Complete Guide Template Engine in Go: A Complete Guide Jun 17, 2023 pm 12:55 PM

    With the development of Internet technology, the demand for web applications is also increasing. Web developers often use template engines to generate dynamic web pages. This article will explore a new template engine: the Go language template engine. What is the Go language template engine? Go language is an advanced programming language developed by Google. Its syntax is concise and clear, making it easy to learn and use. The Go language template engine is a template system used to generate HTML templates in the Go language. The Go language template engine is called the "standard library".

    How to use Smarty template engine in PHP development How to use Smarty template engine in PHP development Jun 27, 2023 pm 01:28 PM

    As a PHP developer, using a template engine is a natural choice. Smarty is a popular template engine that provides a way to separate HTML/CSS/JavaScript from PHP code, allowing developers to better organize and manage projects. In this article, we will learn how to use Smarty template engine during PHP development. 1. Install Smarty Before, we must install Smarty. In this article we will use Composer to install

    See all articles