由于smarty3速度慢,内存消耗大所以还是选择smarty2比较好。
以最小破坏源码为前提,以当前最新版smarty 2.6.27为例
打开smarty目录下Smarty_Compiler.class.php
找到184行
//$this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*';
//以支持多级对象语法标签的提取
$this->_reg_obj_regexp = '[a-zA-Z_]\w*(?:->[a-zA-Z_]\w*){1,}';找到848行
//list($object, $obj_comp) = explode('->', $tag_command);
//提取对象名和后续的对象属性及方法名
list($object, $obj_comp) = explode('->', $tag_command,2); 找到904行,添加一行代码
$return = "\$this->_reg_objects['$object'][0]->$obj_comp"
//多级对象会被解析成属性,在此下手,调用方法必须传入smarty标签属性标注
strpos($obj_comp,'->')>0&&$args and $return.="($args)";应用场景
<?php
class a{
public $field;
function __construct(){
$this->field=new b();
}
}
class b{
public function method($array){
echo 'execute method';
}
}
$smarty=new smarty(){
$smarty->register_object('myobj',new a());
?>
模板里可以这样调用,由register_object 第四个参数决定
{myobj->field->method arg1=1 arg2=2} //这里method函数接受的是数组array('arg1'=>,'arg2'=>2)
或
{myobj->field->method(1,2)}
不传参数就是调用属性了,比如{myobj->field->method}这是调用属性,这里就不支持没有参数的方法调用了,因为没有这种需要。

本文介绍如何在Smarty2中优化多级对象语法,通过修改Smarty_Compiler.class.php文件实现更灵活的对象属性及方法调用。适用于希望提高模板引擎效率的开发者。
1807

被折叠的 条评论
为什么被折叠?



