[Ecshop]让Smarty不用再写assign

由于工作缘故,开始研究起Ecshop的二次开发。从今天起会陆续写几篇关于Ecshop二次开发的文章和大家分享。

Ecshop使用的是Smarty模板引擎——一种被很多人称为“过时”的模板引擎技术(当然,我也是这么认为的)。Smarty作为一种模板引擎技术,使用它的目的是为了实现MVC。而仅仅通过模板技术实现的MVC,还不能成为真正意义上的MVC。Smarty现在也不是PHP官方推荐的模板技术了。不过在官方的框架Zend Framework中,还是保留了对Smarty的支持。

Ecshop的源码中使用了自己精简的Smarty,功能上基本能满足需求。Ecshop仍然是采用面向过程的编码方式,和Discuz类似。而Discuz的中使用模板变量前是不用assign的。那么在Ecshop中像下面的代码我们能不能也省了呢

    $smarty->assign('image_width',  $_CFG['image_width']);
    $smarty->assign('image_height', $_CFG['image_height']);
    $smarty->assign('helps',        get_shop_help()); // 网店帮助
    $smarty->assign('id',           $goods_id);
    $smarty->assign('type',         0);
    $smarty->assign('cfg',          $_CFG);
    $smarty->assign('promotion',       get_promotion_info($goods_id));//促销信息
    $smarty->assign('promotion_info', get_promotion_info());

当然是可以的。我们在Smarty类中的display方法开头加入以下这几句

unset($GLOBALS['_ENV'],$GLOBALS['HTTP_ENV_VARS'],$GLOBALS['HTTP_SERVER_VARS'],$GLOBALS['HTTP_POST_VARS'],$GLOBALS['HTTP_GET_VARS'],$GLOBALS['HTTP_COOKIE_VARS'],$GLOBALS['HTTP_POST_FILES'],$GLOBALS['HTTP_COOKIE_VARS']); //先清空这几个全局变量
$this->assign($GLOBALS); //把全局变量数组"注入模板"

这样,以后在二次开发中我们就不用写那么多繁琐的$smart->assign 了

1 Response to “[Ecshop]让Smarty不用再写assign”


Leave a Reply