PHP--關於模板的原理和解析

來源:互聯網
上載者:User

標籤:

此內容用作筆記,以備日後查看,此內容為學習李炎恢課程而來,並非自己所創,如有問題請私信~

將PHP代碼和靜態HTML代碼進行分離,使代碼的可讀性和維護性得到顯著提高。

使用模板引擎:

    我們所說的模板是Web模板,是主要由HTML標記組成的語言來編寫的頁面,但也有如何表示包含動態產生內容的方式(解析標籤)。模板引擎是一種軟體庫,允許我們從模板產生HTML代碼,並指定要包含的動態內容。

  模板引擎的特點:

  1.鼓勵分離:讓更個系統的可讀性和維護性得到提高。
  2.促進分工:使得程式員和美工去專心處理自己的設計。
  3.比PHP更容易解析:編譯檔案和快取檔案載入更快、佔資源更少。
  4.增加安全性:可限制模板設計師進行不安全的操作的能力避免誤刪誤訪問等。

模板處理的流程圖

  

 

建立模板:

  1、建立初始模板所需要的檔案夾和檔案。

  a) index.php主檔案,用於編寫商務邏輯。
  b) template.inc.php模板初始設定檔案,用於初始模版資訊。
  c) templates目錄存放所有的模板檔案。
  d) templates_c目錄存放所有編譯檔案。
  e) cache目錄存放所有快取檔案。
  f) includes目錄存放所有的類檔案。
  g) config目錄存放模板系統變數設定檔。

  

  以下是源碼:

主檔案 index.php  

<?php   //index.php

  //設定編碼為UTF-8
  header(‘Content-Type:text/html;Charset=utf-8‘);
  //網站根目錄
  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/‘);
  //定義緩衝狀態
  define(‘IS_CACHE‘,true);
  //設定緩衝狀態開關
  IS_CACHE ? ob_start() : null;

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

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

模板檔案 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頁面裡是不顯示的,只會在產生的編譯檔案裡顯示{#}我將被index.php匯入{$name}這個標籤必須經過Parser.class.php這個解析類來解析它1<br />這裡的內容改變了,為什嗎?<br />{if $a}顯示一號皮膚{else}顯示二號皮膚{/if}<br />{foreach $array(key,value)}{@key}....{@value} <br />{/foreach}</body></html>

  

模板類:

         //Templates.class.php   class Templates {    //建立一個存放數組的欄位    private $_vars = array();    private $_config = array();    //建立一個構造方法    public function __construct(){        if(!is_dir(TPL_DIR) || !is_dir(TPL_C_DIR) || !is_dir(CACHE_DIR) ){            exit(‘ERROR:模板檔案夾或者編譯檔案夾或者快取檔案夾沒有建立!‘);        }        //擷取系統變數        $_sxe = simplexml_load_file(ROOT_PATH.‘/config/profile.xml‘);        $_taglib = $_sxe->xpath(‘/root/taglib‘);        foreach($_taglib as $_tag){            $this->_config["$_tag->name"] = $_tag->value;        }    }          //建立變數注入方法    /**     * assign()變數注入方法     * @param  $_var 要注入的變數名,對應.tpl檔案中的需要替換的變數      * @param  $_values 要注入的變數值     */    public function assign($_var,$_values){        if(isset($_var) && !empty($_var)){            $this->_vars[$_var] = $_values;                    }else{            exit(‘ERROR:請設定變數名!‘);        }            }            //建立一個顯示方法,用來顯示編譯後的檔案    public function display($_file){        //設定模板檔案的路徑        $_tplFile = TPL_DIR.$_file;        //判斷模板檔案是否存在        if(!file_exists($_tplFile)){            exit(‘ERROR:模板檔案不存在‘);        }        //設定編譯檔案名稱        $_parFile  = TPL_C_DIR.md5($_file).$_file.‘.php‘;        //設定快取檔案名        $_cacheFile = CACHE_DIR.md5($_file).$_file.‘.html‘;        //判斷緩衝狀態        if(IS_CACHE){            //判斷快取檔案是否存在            if(file_exists($_cacheFile) && file_exists($_parFile)){                //是否修改過編譯檔案或者模板檔案                if(filemtime($_cacheFile)>=filemtime($_parFile) && filemtime($_parFile)>filemtime($_tplFile)){                    echo ‘以下是快取檔案內容‘;                    echo "<br />";                    include $_cacheFile;                    return;                }            }        }        //判斷編譯檔案是否存在,模板檔案是否修改過        if(!file_exists($_parFile) || (filemtime($_parFile) < filemtime($_tplFile))){                        //引入模板解析類            require ROOT_PATH.‘/includes/Parser.class.php‘;            //執行個體化對象,產生編譯檔案            $_parser = new Parser($_tplFile);//模板檔案            $_parser->compile($_parFile);//編譯後檔案                    }        //載入編譯檔案        include $_parFile;        if(IS_CACHE){            //產生快取檔案            file_put_contents($_cacheFile, ob_get_contents());            //清除緩衝區            ob_end_clean();            //載入快取檔案            include $_cacheFile;        }    }}

解析類:

//Parser.class.phpclass Parser {    //擷取模板內容    private $_tpl;    //構造方法,初始化模板    public function __construct($_tplFile){        //判斷檔案是否存在        if(!$this->_tpl = file_get_contents($_tplFile)){            exit(‘ERROR:讀模數板出錯!‘);        }            }        //解析普通變數    private function parVar(){        $_pattern = ‘/\{\$([\w]+)\}/‘;    if (preg_match($_pattern,$this->_tpl)) {    $this->_tpl = preg_replace($_pattern,"<?php echo \$this->_vars[‘$1‘] ?>",$this->_tpl);    }    }    //解析IF條件陳述式    private function parIf(){        //開頭if模式        $_patternIf = ‘/\{if\s+\$([\w]+)\}/‘;        //結尾if模式        $_patternEnd = ‘/\{\/if\}/‘;        //else模式        $_patternElse = ‘/\{else\}/‘;        //判斷if是否存在        if(preg_match($_patternIf, $this->_tpl)){            //判斷是否有if結尾            if(preg_match($_patternEnd, $this->_tpl)){                //替換開頭IF                $this->_tpl = preg_replace($_patternIf, "<?php if(\$this->_vars[‘$1‘]){ ?>", $this->_tpl);                //替換結尾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:語句沒有關閉!‘);            }        }    }    //解析foreach    private function parForeach(){        $_patternForeach = ‘/\{foreach\s+\$(\w+)\((\w+),(\w+)\)\}/‘;        $_patternEndForeach = ‘/\{\/foreach\}/‘;        //foreach裡的值        $_patternVar = ‘/\{@(\w+)\}/‘;        //判斷是否存在        if(preg_match($_patternForeach, $this->_tpl)){            //判斷結束標誌            if(preg_match($_patternEndForeach, $this->_tpl)){                //替換開頭                $this->_tpl = preg_replace($_patternForeach, "<?php foreach(\$this->_vars[‘$1‘] as \$$2=>\$$3){?>", $this->_tpl);                //替換結束                $this->_tpl = preg_replace($_patternEndForeach, "<?php } ?>", $this->_tpl);                //替換值                $this->_tpl = preg_replace($_patternVar, "<?php echo \$$1?>", $this->_tpl);            }else{                exit(‘ERROR:Foreach語句沒有關閉‘);            }        }    }    //解析include    private function parInclude(){        $_pattern = ‘/\{include\s+\"(.*)\"\}/‘;        if(preg_match($_pattern, $this->_tpl,$_file)){            //判斷標頭檔是否存在            if(!file_exists($_file[1]) || empty($_file[1])){                exit(‘ERROR:包含檔案不存在!‘);            }                //替換內容                $this->_tpl = preg_replace($_pattern, "<?php include ‘$1‘;?>", $this->_tpl);        }    }    //解析系統變數    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();        //解析系統變數        $this->configVar();        //產生編譯檔案        if(!file_put_contents($_parFile, $this->_tpl)){            exit(‘ERROR:編譯檔案產生失敗!‘);        }    }}

  

總結:模板引擎的整個過程:

  1、當瀏覽器請求index.php檔案時,執行個體化模板類對像 $_tpl = new Templates();

  2、當Templates執行個體化的時候,產生兩個數組,一個用來存放模板變數,另一個存放系統變數,通過構造方法,判斷檔案夾是否存在,同時通過XML檔案將系統變數數組初始化

  3、通過模板類Templates的注入方法,assign(),將對應模板index.tpl中變數的index.php的內容注入到模板類的私人變數,完成初始化

  4、模板類Templates類顯示方法display() 通過執行個體化解析類Parser,將取到的注入變數通過解析類進行解析(即替換)

  5、解析(替換)後,將檔案寫入PHP、HTML混全檔案

  6、通過Templates類的顯示方法將檔案輸出:

     1、第一次執行顯示方法時,將會把PHP、HTML混合檔案,產生純靜態快取檔案

     2、調用快取檔案,顯示頁面

     3、當瀏覽器再次調用顯示方法時,首先根據各檔案的最後修改時間,判斷是否重建快取檔案或直接調用已存在的快取檔案

重點:

  1、通過Regex進行字串的替換

  2、熟悉OOP

  

 

PHP--關於模板的原理和解析

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.