我放弃Smarty的一次经验,和兄弟们分享一下,请兄弟们PP^^
原文在我的论坛:http://www.ipbfans.org/topic22
我一直很郁闷的就是,写程序的时候必须在模板和PHP之间来回奔波,每用一种模板,都要适应它们的语法,抱怨它们的不足。
至于模板的好处,我就不说了,网上多的是。
为什么不用传统的html和php混合编写的方式?各有各的看法。
根据我的经验,如果用模板,至少有两个缺点:
1、速度
不管哪一种模板,都要将模板语言转换成PHP语句,即使是号称有“编译”功能的Smarty、smarttemplate等等。尤其是Smarty,Smarty过于庞大和复杂,即使经过编译,php程序每次还是得初始化Smarty类、经过一系列判断……
如果你去看看Smarty缓存文件,或许你会觉得,里面的代码象你刚学php的时候写的……
2、功能
在用模板写程序的时候,“多种循环”和“文件嵌套”经常会将人折磨的很郁闷,反正我在刚开始用这些模板的时候就是。
如果直接用混合PHP和html的方式,这种问题马上就迎刃而解了。
最近做的一个项目里面,一直被Smarty的庞大和效率所困扰,最终决定放弃这个庞然大物,选择了最古老的PHP与HTML代码混合的方式。但是姑且还是将其称为“模板”吧。
用Smarty的时候,我是自己写了一个类,按照phplib的方法名重写封装了一下Smarty。决定放弃Smarty以后,模板文件肯定要全部重写,但是为了尽量减少程序的修改,我将这个类全部重新改写了,去处了所有与Smarty相关的代码,取而代之的是下面这个简单的类:
CODE
<?php
class ezj_template
{
/**
* @access public
* @var string
*/
var $t_dir = '';
var $skin = '';
var $common = '';
var $template_cfg = array();
var $main = '';
var $vars = array();
function ezj_template()
{
global $ezj;
$this->t_dir = ROOT_PATH . $ezj->cache['template']['tpl_path'] . '/';
@include( $this->t_dir . '_config.php' );
$this->template_cfg = $_template_config;
}//-- end of constructor
/*
* 将模板内容输出到浏览器
@param string $cache_id
@param string $compile_id
@access public
@return void
*/
function output($cache_id = null, $compile_id = null)
{
global $ezj , $db;
require_once( VIEWS . 'template/class.template_common.php' );
$this->common = new template_common(&$this);
$this->common->run();
@header("HTTP/1.0 200 OK");
@header("HTTP/1.1 200 OK");
@header("Content-type: text/html;charset=utf-8");
if ($ezj->vars['header_no_cache'])
{
@header("Cache-Control: no-cache, must-revalidate, max-age=0");
@header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
@header("Pragma: no-cache");
}
if ( $ezj->vars['gunzip_enabled']==1 )
{
$buffer = @ob_get_contents();
@ob_end_clean();
@ob_start('ob_gzhandler');
print $buffer;
}
extract($this->vars);
$t = &$this->t_dir;
@include_once( $t . $this->main );
if ( defined('WITHOUT_SHUTDOWN') )
{
$ezj->_destruct();
}
}//-- end of method `output`
function set_var($tpl_var, $value = null)
{
$this->assign($tpl_var , $value);
}
function set_file($file)
{
$this->main = $file;
}
function assign($var , $value=null)
{
if ( is_array($var) )
{
foreach($var as $k=>$v)
{
$this->vars[$k] = $v;
}
}else
{
$this->vars[$var] = $value;
}
}
}//-- end of class `ezj_template`
?>