1. Smarty的工作原理是: Smarty自帶編譯類,作用是將模版中的標籤替換成PHP代碼,每次檢查PHP源碼的修改時間,只有PHP修改了,才重新編譯,所以Smarty的性能還可以。下面我們自己編寫一個簡單的編譯類,實現替換模板中標籤的功能,實現一個最小功能的Smarty模板,一次來理解Smarty的運行原理。
首先不使用模板時,來看一個最簡單的用PHP輸出的例子:
<?php
$title="this is the title";
$content="smarty yuanli is this";
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $title?></title>
</head>
<body>
<p>內容:<?php echo $content?></p>
</body>
</html>
HTML代碼負責表示層,PHP代碼負責取出需要的數據輸出,這裏是title和content。可以看到,這是PHP代碼和HTML代碼是混合在一起的。模板的目的就是從中分離出PHP代碼,換成其他語法更簡單的,更接近HTML語法的標籤語言實現與嵌入PHP相同的功能。
爲什麼不直接使用PHP而要再引入一種新的語法的呢?
一是爲了讓專注於頁面設計的人員不必學習PHP而只學習Smarty語法就能完成設計,Smarty語法與PHP相比簡單很多也容易學習,更接近頁面設計人員掌握的HTML,CSS等語法
二是如果在頁面中也使用PHP,編程人員很難保證不會把其他不屬於顯示的PHP代碼放在HTML頁面中。
簡單來看,實現一個模板引擎,只需要編寫一個類,實現將HTML中新定義的模板語法翻譯成PHP代碼即可,實際上就是用正則表達式匹配替換字符串的過程。
smarty.class.php(簡單實現):
<?php
class Smarty{
public $template_dir;//模板目錄
public $compile_dir;//編譯目錄
public $arr=array();//定義一個數組,用以存放assign中的第二個參數傳過來的值
public function __construct($template_dir="../templates",$compile_dir="../templates_c"){
$this->template_dir=$template_dir;//模板目錄
$this->compile_dir=$compile_dir; //編譯目錄
}
public function assign($content,$replacment=null){
if($content!=""){ //如果指定模板變量,纔將要賦的值存儲到數組中
$this->arr[$content]=$replacment;
}
}
public function display($page){
$tplFile=$this->template_dir."/".$page;//讀取模板文件,注意:如果模板目錄下還有子目錄,記得要寫完整,比如,$smarty->display('Default/index.tpl')
if(!file_exists($tplFile)){
return;
}
$comFile=$this->compile_dir."/"."com_".$page.".php";
$tplContent=$this->con_replace(file_get_contents($tplFile));//將smarty標籤替換爲php的標籤
file_put_contents($comFile,$tplContent);
include $comFile;
}
public function con_replace($content){
$pattern=array(
'/<{\s*\$([a-zA-Z_][a-zA-Z_0-9]*)\s*}>/i'
);
$replacement=array(
'<?php echo $this->arr["${1}"] ?>'
);
return preg_replace($pattern,$replacement,$content);
}
}
?>
smarty.ini.php: 用來配置Smarty,這裏和真正的Smarty使用前的配置差不多,只是比較簡單。
<?php
include "Smarty.class.php";
$tpl=new Smarty();
$tpl->template_dir="./templates";
$tpl->compile_dir="./compile";
?>
模板文件index.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><{$title}></title>
</head>
<body>
<p>內容:<{$content}></p>
</body>
</html>
index.php :
<?php
include "./smarty.ini.php";
$title="this is the title ";
$content="this is the content ";
$tpl->assign("title",$title);
$tpl->assign("content",$content);
$tpl->display("index.html");
?>
此時網站的目錄結構是這樣的:
Smarty-test---------compile-------com_index.html.php(經過smarty.class.php編譯後生成的文件)
------------------------template------index.html
------------------------index.php
-----------------------smarty.class.php
-----------------------smarty.ini.php
好的,我們來看看編譯後的smarty.class.php文件:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title><?php echo $this->arr["title"] ?></title>
</head>
<body>
<p>內容:<?php echo $this->arr["content"] ?></p>
</body>
</html>
是不是和沒有使用模板前PHP與HTML混合時的時候相同。
這就是一個非常簡單的模版引擎了。Smarty的基本原理就是這樣,只不過在此基礎上多了很多方便使用的語法。