PHP 超級模板引擎

來源:互聯網
上載者:User
在進入正題之前先明確幾個關鍵點,有助於協助我們理解這個PHP模板引擎產生的原因.

//如果要轉載本文請註明出處,免的出現版權紛爭,我不喜歡看到那種轉載了我的作品卻不註明出處的人 Seven{See7di#Gmail.com}

什麼是PHP模板引擎:
為了能夠讓表現層和邏輯層分離,方便將來修改前台介面的時候不會改動的邏輯層的邏輯.

一個好的模板引擎需要具備哪些素質:
能夠很好的把表現層和邏輯層分離
不可以影響前台的訪問瀏覽速度
使用簡單

參數對比:
現在市面上PHP的模板引擎不計其數,基本上每個模板引擎都能實現邏輯層和表現層的分離,那麼接下來我們需要考慮的就是方便使用和解析速度的問題了.
首先我們看速度方面,目前市面上速度最快的模板引擎應該就是smarty(其他那些模板引擎的速度不敢恭維,拋開不談),但是他臃腫,他有一套屬於他自己的範本語言,對於每一個使用者來說都要學會他的範本語言才能夠正常使用,這一點來講它在使用簡單方面就沒有任何的優勢,因此針對以上問題我製作了自己的模板引擎,即您即將看到的超級模板引擎.

模板引擎類的核心代碼如下:
<?php
/**
* Copyright (c) 2010-10-13 F. seven (See7di@Gmail.Com)
*/

Class Template{
var $vars;        // 用來儲存所有的模板變量
var $path;        // 模板檔案存放的路徑,必須/結束
var $debug;        // 是否開啟偵錯模式
var $expire;
var $cached;
var $cacheid;

/* 構造函數
* @參數 (string) $path 模板檔案的路徑
* @參數 (int) $expire 緩存的有效期間(秒)
* @返回 (null)
*/
Function Template($expire=900,$debug=False,$path="./tpl/"){
$this->path = $path;
$this->vars = array();
$this->debug = $debug;
$this->expire = $expire;

//根據邏輯層檔案的md5值計算cacheid,可防止產生垃圾緩衝
$this->cacheid = 'cache/'.Md5_file(Realpath("./").Basename($_SERVER["PHP_SELF"]));
}

// 重新設置模板檔案存放路徑
Function setPath($path){
$this->path = $path;
}

/*
* 設置模板內使用的變量
* @參數 (string) $name 需要設置的變量名
* @參數 (mixed) $value 該變量的值
* @返回 (null)
*/
Function set($name, $value){
$this->vars[$name] = $value;
}

/*
* 將模板變數合并或重寫存放到一個數組內
* @參數 (array) $vars 待操作數組名
* @參數 (bool) $clear 是否允許重寫已存在的變量
* @返回 (null)
*/
Function setVar($vars, $clear = False){
IF($clear){
$this->vars = $vars;
}Else{
IF(Is_array($vars)){
$this->vars = Array_merge($this->vars, $vars);
$this->vars = $this->FormatKey($this->vars);
}
}
}

/*
* 將數字索引的數組索引值修改成符合變數標準的索引值
* @例子 Array("a"=>"a","b",3=>"c")轉換之後是Array("a"=>"aa","_0"=>"b","_3"=>"c")
* @參數 (array) 待格式化的數組
* @返回 (array)
*/
Function FormatKey($arr){
$_keys=Array_keys($arr);
Foreach($_keys as $key=>$value){
IF(Is_numeric($value)){
$_keys[$key]="_".$value;
}
}
Return Array_combine($_keys,$arr);
}

/*
* 根據cacheid判斷當前的緩存是否有效
* @返回 (bool)
*/
Function Is_cached(){
IF($this->cached){Return True;}
IF(!$this->cacheid){Return False;}
IF(!File_exists($this->cacheid)){Return False;}
IF(!($mtime = Filemtime($this->cacheid))){Return False;}

// 緩存是否已過期?
IF(($mtime + $this->expire) < time()){
@Unlink($this->cacheid);
Return False;
}Else{
$this->cached = True;
Return True;
}
}

/*
* 打開,解析,並返回模板檔案
* @參數 (string) 模板檔案名稱
* @返回 (string)
*/
Function Fetch($file){
IF(!File_Exists($this->path . $file)){Return False;}
Extract($this->vars);            // 提取變量到當前命名空間
OB_start();                        // 開始輸出緩沖
OB_clean();                        // 清理原有內容
Include($this->path . $file);    // 調用模板檔案
$contents = ob_get_contents();    // 取得緩存區內容
ob_end_clean();                    // 結束緩沖區
Return $contents;                // 返回模板檔案執行結果後的內容
}

/*
* 根據cacheid返回被緩存的內容,如果尚未緩存則馬上緩存
* @參數 (string) $file 模板檔案名稱
* @返回 (string)
*/
Function FetchCache($file){
IF($this->Is_cached()){
IF($this->debug){Echo "<br>{直接讀緩衝}<br>";}
$fp = @Fopen($this->cacheid, 'r');
$contents = fread($fp, Filesize($this->cacheid));
Fclose($fp);
Return $contents;
}Else{
IF($this->debug){Echo "<br>{寫入並返回緩衝}<br>";}
$contents = $this->Fetch($file);
IF($fp = @Fopen($this->cacheid, 'w')){
Fwrite($fp, $contents);
Fclose($fp);
}Else{
Die('Unable to write cache.');
}
Return $contents;
}
}
}
?>

模板引擎的執行個體化:
<?php
//注意:一旦手工修改過執行個體化檔案後最好是刪掉所有快取檔案,讓其重新緩衝一次
Require_once('Template.php');

$tpl = &New Template();
$tpl->set('title', 'User Profile');
$arr = Array();

$arr = Array(
"a"=>1,
"b"=>"b",
"c"=>array(12,23)
);
$arr["d"]=array("第一個","第二個");

For($i=0;$i<10;$i++){
$arr[$i]="值{$i}";
}

$tpl->setVar($arr);
//echo $tpl->fetch('tpl1.php');
Echo $tpl->fetchCache('tpl1.php');
?>

模板是這樣的:
相關的模板是這樣的:<br>
<table cellpadding="3" border="0" cellspacing="1">
<tr>
<td><a href='1.php' title=''>1.php</a></td>
<td><a href='index.php' title=''>index.php</a></td>
</tr>
<tr>
<td>索引值A:</td>
<td><?=$a;?></td>
</tr>
<tr>
<td>索引值B:</td>
<td><?=$b;?></td>
</tr>
<tr>
<td>索引值C:</td>
<td><?PHP
For($i=0;$i<count($c);$i++){
Echo $c[$i]."<br>";
}
?></td>
</tr>
<tr>
<td>索引值D:</td>
<td><?PHP
For($i=0;$i<count($d);$i++){
Echo $d[$i]."<br>";
}
?></td>
</tr>
<tr>
<td>後期擴充的</td>
<td><?PHP
For($i=0;$i<10;$i++){
Echo ${"_".$i}."<br>";
}
?></td>
</tr>
</table>

我為什麼要這樣做呢?
因為我認為PHP的迴圈比任何模板引擎裡邊的範本語言迴圈更簡單且更容易理解,這一點對於製作前台表現的美工來說並不難學習,而對於那些原來就懂得PHP程式編寫的程式員來說簡直就是手到擒來,根本就不需要再學習一門新的範本語言.既然如此何樂而不為呢?
另外這樣的模板引擎速度比市面上速度最快的模板引擎smarty速度更是快了很多倍,以迴圈10000次做測試,僅僅比直接使用PHP的echo輸出慢接近8毫秒,既然是10000次慢8毫秒,那麼這完全可以忽略不計.

因為他使用簡單,外加速度非常快,所以就叫他"超級模板引擎"吧!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.