2013年7月24日 星期三

PHP 內建的樣板引擎

最近剛好在研究PHP的樣板引擎,發現到原本PHP其實就可以做樣板引擎
他主要的原理是透過輸出緩衝資料的Buffer做資料組合,轉換成HTML格式

下面是自己測試的PHP檔:
------------------------------------------------------------------
coreTemplate.php 組合樣板用的類別
------------------------------------------------------------------
<?php
class CoreTemplate{
/**組合樣板資料
* @param $template 樣板路徑
* @param $data 導入到樣板的資料變數(樣板的PHP檔須從這個變數取得所需資料)
* @return 組合完成的資料
*/
function render($template, $data) {
ob_start();
include $template;
$result = ob_get_contents();
ob_end_clean();

return $result;
}
}
?>

------------------------------------------------------------------
test.tpl.php 樣板的php程式碼
------------------------------------------------------------------
<html>
   <head>
        <title>Test</title>
    </head>
    <body>
        <table>
            <tr>
                <td>ID</td><td>Name</td>
            </tr>
            <!-- PHP 樣板文字 $data為coreTemplate所設定的資料變數名稱-->
            <?php foreach($data as $list): ?>
            <tr>
                <td><?=$list['id']?></td><td><?=$list['name']?></td>
            </tr>
            <?php endforeach; ?>
        </table>
    </body>
</html>

------------------------------------------------------------------
test.php 程式邏輯跟輸出
------------------------------------------------------------------
<?php
include_once("coreTemplate.php");

$ct = new CoreTemplate();
$info = array();
//產生10筆資料
for($i = 0; $i < 10;$i++){
array_push($info, array('id'=>$i, 'name'=>'name'. $i));
}
//輸出HTML
echo $ct->render('test.tpl.php' , $info);
?>
----------------------------------------------------------------------
輸出結果
----------------------------------------------------------------------


結論:
這次的實驗主要只是看php做樣板引擎的方法而已,真正要自己實作應該也會需要時間
所以還是用Smarty做樣板引擎~XD!