今天手痒将一个旧的PHP项目的Smarty模板引擎进行了升级,到Smarty官方网站下载最新版本3.1.8,本来以为妥妥的,但结果杯具了,PHP报错如下:
Fatal error: Uncaught exception 'SmartyException' with message 'Call of unknown method 'register_block'.' in E:\Smarty-3.1.8\libs\sysplugins\smarty_internal_templatebase.php:806
好吧,我承认我又手贱了一回,根据错误信息:“Call of unknown method ‘register_block’.”知道是找不到类的register_block方法,这怎么可能呢?原来这个函数可是妥妥的,难道Smarty3做了改变?
我又折返到Smarty官方网站,果然是这样的,官网同时提供Smarty2和Smarty3下载,我原来的项目是Smarty2的旧版本,里面是有register_block、register_function等函数的,Smarty3新版上在命名上做了规范,这些都可以到Smarty官网手册上查询到。好了,说了这么多,现在对于这个问题的解决方案有两个,一是使用Smarty2系列,二是使用Smarty3的新接口。这里引用一下官方文档的例子,比如说register_block在Smarty3中应该这么写:
<?php // function declaration function do_translation ($params, $content, $smarty, &$repeat, $template) { if (isset($content)) { $lang = $params["lang"]; // do some translation with $content return $translation; } } // register with smarty $smarty->registerPlugin("block","translate", "do_translation"); ?> |
同样的官方文档的例子,register_function在Smarty3中应该这么写:
<?php $smarty->registerPlugin("function","date_now", "print_current_date"); function print_current_date($params, $smarty) { if(empty($params["format"])) { $format = "%b %e, %Y"; } else { $format = $params["format"]; } return strftime($format,time()); } ?> |
实际上统一调用了Smarty3的方法registerPlugin,关于这个方法更多的调用可以参考Smarty手册。
现在解决这个问题除了降级Smarty和改使用新类方法外还可以建立个SmartyWrapper的Smarty子类,自己写两个register_block和register_function方法,然后直接new SmartyWrapper这样比一个一个改接口好多了。
PS:刚刚发现谷歌的首页Logo换成了一架电子琴,还能弹奏哦,强大的Google,欢迎大家去围观。