//php 控制器文件php
<?php
//引入模板引擎文件
include("20130304.php");
$smarty = new TinySmarty();
$qq_numbers=array('a1'=>'12333','a2'=>'2222222','a3'=>'333333','a4'=>'3333333');
$smarty->assign($qq_numbers);
$smarty->assign('title','這是個人QQ號碼');
$smarty->assign('contents','這是個人QQ:1211884772');
$smarty->display('20120305_01.html');html
?>正則表達式
模板引擎類20130304.php數組
<?php
/***
smarty模板引擎原理
1:讀取模板文件
2:替換模板標籤爲php可執行代碼
3:保存替換成功的php文件
***/
/*
問題?
1:每次訪問都編譯浪費cpu?
編譯文件存在,不用在編譯直接引入
2:模板文件修改後,必須從新編譯該文件
當模板文件修改時間大於編譯文件修改時間,說明模板文件被修改了,
所以要從新編譯模板文件
*/
class TinySmarty{
//模板文件存放目錄
public $template_dir="./templates/";
//編譯後文件存放目錄
public $compile_dir="./c_templates/";ui
//存放變量值
public $tpl_vars=array();this
//assign
//將變量以數組形式存放到該$tpl_var屬性
public function assign($tpl_var,$var=null){
//傳入數組形式,爲批量賦值
if(is_array($tpl_var)){
foreach($tpl_var as $_key=>$_val){
if($_key!=''){
$this->tpl_vars[$_key] = $_val;
}
}
}else{
//傳入非空字符
if($tpl_var!=''){
$this->tpl_vars[$tpl_var] = $var;
}
}
}spa
/*
name display
param string $tpl_file 文件名htm
*/
public function display($tpl_file){
//模板文件路徑
$template_file_path = $this->template_dir.$tpl_file;
//編譯文件路徑
$compile_file_path = $this->compile_dir.$tpl_file;
//判斷編譯文件是否存在
if(!file_exists($compile_file_path)||filemtime($template_file_path)>filemtime($compile_file_path)){
//判斷文件是否存在
if(!file_exists($template_file_path)){
return false;
}
//讀取文件內容
$fpl_file_con = file_get_contents($template_file_path);模板引擎
//替換模板標籤
//如:{$title} 替換爲<?php echo $title; ? >
//正則表達式//此處正則涉及到正則的反響引用
$pattern = '/{\s*\$([_a-zA-Z][_0-9a-zA-Z]*)\s*\}/i';
$replace = '<?php echo $this->tpl_vars["${1}"];?>';
$new_file_con= preg_replace($pattern,$replace,$fpl_file_con);
//寫入文件內容
file_put_contents($compile_file_path,$new_file_con);
}utf-8
//引入編譯後的文件
include ($compile_file_path);
}
}
?>
模板文件20120305_01.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{$title}</title>
</head>
<body>
<h1>hello-</h1>
{$contents}
</body>
</html>