PHP 模板技术!
2008-06-26 19:34:04| 分类: 默认分类|举报 |字号
PHP模板类的原理很简单:类+模板替换。
说到替换,我第一个想到的就是正则表达式。PHP里字符替换函数大部分都是基于正则的。
所以,我个人认为,实现PHP模板类的原理是:类+正则表达式。
写了第一个PHP模板类,功能简单得不能再简单了:
cls.php -- 定义模板类
/***************
* cls.php *
***************/
class lly_template
{
var $template_file_name;
var $content;
function lly_template($filename = "template.html")
{
$this -> template_file_name = $filename;
}
function load()
{
$fs = fopen($this -> template_file_name,"r");
$content_ = fread($fs, filesize($this -> template_file_name));
fclose($fs);
$this -> content = $content_;
}
function repl($html_rep, $php_rep)
{
$this -> content = ereg_replace("\{".$html_rep."\}",$php_rep,$this -> content);
}
}
?>
test.php -- 调用模板类
/***************
* test.php *
***************/
include("cls.php");
$html = new lly_template();
$html -> load();
$html -> repl("subject","主题");
$html -> repl("content","内容");
echo $html -> content;
?>
template.html -- 模板文件
{subject}{subject}
{content}