PHP Simple Template Engine

โดย SONGCHAI SAETERN
สำหรับคลาส Template Engine จะประกอบด้วย 3 ส่วนด้วยกัน คอ

1) ส่วนของ PHP ( Controller & Model )
2) ส่วนของ HTML ( Views )
3) คลาสจัดการ Template









HTML Views

<html>
<head>
<title>{page_title}</title>
</head>
<body>
<h3>{table_heading}</h3>

<table border="1">
<tr>
<th>รายการ</th>
<th>จำนวน</th>
<th>ราคาต่อหน่วย</th>
<th>ราคารวม</th>
</tr>
<tr parser-repeat="[data_lists]">
<td>{title}</td>
<td>{qty}</td>
<td>{unit_price}</td>
<td>{subtotal}</td>
</tr>
</table>
</body>
</html>


PHP Controller & Model  

<?php
include('libraries/PHP_Parser.php');
$template = new PHP_Parser();
// Query from Database
$data_lists = array(
array('title' => 'กระดาษ A4', 'qty' => 2, 'unit_price'=>100, 'subtotal'=>200),
array('title' => 'ดินสอ', 'qty' => 15, 'unit_price'=>2, 'subtotal'=>30),
array('title' => 'ยางลบ', 'qty' => 8, 'unit_price'=>5, 'subtotal'=>40),
array('title' => 'ปากกา', 'qty' => 10, 'unit_price'=>12, 'subtotal'=>120),
array('title' => 'ไม้บรรทัด', 'qty' => 3, 'unit_price'=>20, 'subtotal'=>60)
);
$data = array(
'page_title'   => 'ใบส่งของ',
'table_heading' => 'ใบส่งของ เลขที่ 64/00001',
'data_lists' => $data_lists
);

$template->parse('views/home.html', $data);
?>




Class Template engine PHP_Parser.php

<?php
/**
 * PHP HTML Template Engine
 * http://www.phpcodemania.com
 * @2021 for PHP Beginner
 */
class PHP_Parser{
/**
* Left delimiter character for pseudo vars
*
* @var string
*/
public $left_delimiter = '{';

/**
* Right delimiter character for pseudo vars
*
* @var string
*/
public $right_delimiter = '}';
public function parse($file_path, $data, $return = FALSE)
{
$html = $this->_load_view($file_path);
$template = $this->_parse_attribute($html, $data);
if($return == TRUE){
return $template;
}else{
echo $template;
}
}
private function _load_view($file_path)
{
$base_path = getcwd();
$file_path = $base_path.'/'. $file_path;
if(file_exists($file_path)){
ob_start();
include($file_path);
$template = ob_get_clean();
}else{
$template = 'View not found : '. $file_path;
}
return $template;
}
/**
* Parse array data list with attribute
*
* @param string
* @param array
* @param boolean
* @return array
*/  
protected function _parse_attribute($template, $data)
{
if ($template === '')
{
return FALSE;
}

$replace = array();
foreach ($data as $key => $val)
{
$replace = array_merge(
$replace,
is_array($val)
? $this->_parse_attribute_pair($key, $val, $template)
: $this->_parse_variable($key, (string) $val, $template)
);
}

unset($data);
$template = strtr($template, $replace);
return $template;
}
private function _parse_variable($key, $val, $string)
{
return array($this->left_delimiter.$key.$this->right_delimiter => (string) $val);
}
/**
* Parse data to pseudo-variables between attribute parser-repeat="[*]"
*
* @param string
* @param array
* @param string
* @return array
*/
protected function _parse_attribute_pair( $attr_value, $data, $string)
{
$replace = array();
$matches = $this->_get_html_between('parser-repeat', $attr_value, $string);

if(!empty($matches)){
foreach ($matches as $match)
{
$str = '';
foreach ($data as $row)
{
$temp = array();
foreach ($row as $key => $val)
{
if (is_array($val))
{
$pair = $this->_parse_attribute_pair($key, $val, $match[0]);
if ( ! empty($pair))
{
$temp = array_merge($temp, $pair);
}
continue;
}
$temp[$this->left_delimiter.$key.$this->right_delimiter] = $val;
}
$temp[' parser-repeat="['.$attr_value.']"'] = '';//Clear repeat attribute
$str .= strtr($match[0], $temp);
}
$replace[$match[0]] = $str;
}
}
return $replace;
}
/**
* Match html element between attribute parser-repeat="[*]"
* @param string
* @param string
* @param string
* @param string
* @return array
*/
private function _get_html_between( $attr, $value, $xml, $tag=null ) 
{
if( is_null($tag) ){
$tag = '\w+';
}else{
$tag = preg_quote($tag);
}
$attr = preg_quote($attr);
$value = preg_quote($value);

//SEARCH TAG TARGET (IT WILL BREAK WITH FIRST CLOSE TAG)
$tag_regex = "/<(".$tag.")[^>]*".$attr."\s*=\s*(['\"])\[$value\]\\2[^>]*>(.*?)(<\/\\1>)/si";
preg_match_all($tag_regex,
$xml,
$results,
PREG_SET_ORDER);
 
if(isset($results[0][1])){
$check = count($results); // IF HAS MORE THAN ONE TAG MUST USE \+w
if($check == 1){
$tag = $results[0][1]; // SET IF ONE TAG NAME
}
//GET CONTENT AGAIN WITH MULTI CLOSE TAG
$multi_regex = '{<'.$tag.'[^>]*'.$attr.'="\['.$value.'\]"[^>]*>((?:(?:(?!<'.$tag.'[^>]*>|<\/'.$tag.'>).)++|<'.$tag.'[^>]*>(?1)<\/'.$tag.'>)*)<\/'.$tag.'>}si';
preg_match_all($multi_regex,
$xml,
$matches_result,
PREG_SET_ORDER);
$results = $matches_result;
}

return $results;
}
}

/* End of file PHP_Parser.php */







PHP CI MANIA - PHP Code Generator 

โปรแกรมช่วยสร้างโค้ด "ลดเวลาการเขียนโปรแกรม"
ราคาสุดคุ้ม  
http://fastcoding.phpcodemania.com