Magento Block构造 - 使用_construct还是__construct?

Nik*_*rov 7 magento magento-1.7

我有点困惑.我阅读了Alan Storm关于Magento块生命周期方法的优秀文章,据我所知,应该使用该protected _construct()方法来初始化块.在我的情况下,我只想设置正确的块模板.所以我假设我应该使用

protected function _construct()
{
    parent::_construct();
    $this->setTemplate('stenik/qaforum/forum.phtml');
}
Run Code Online (Sandbox Code Playgroud)

但是,当我查看一些核心Magento模块的块时,它们似乎使用php __construct方法来完成它.例如Mage_Poll_Block_Poll,Mage_ProductAlert_Block_Price,Mage_Rating_Block_Entity_Detailed,Mage_Review_Block_Form

虽然两种方式实际上都有效,但我想知道什么是正确的方法.

ben*_*rks 9

它最终是学术性的,但正确的做法就是覆盖Magento构造函数,即_construct根据核心团队的要求Mage_Core_Block_Abstract:

/**
 * Internal constructor, that is called from real constructor
 *
 * Please override this one instead of overriding real __construct constructor
 *
 */
protected function _construct()
{
    /**
     * Please override this one instead of overriding real __construct constructor
     */
}
Run Code Online (Sandbox Code Playgroud)

  • +1是正确的建议,但这不是百分之百的学术 - 当你重写`__construct`方法时,你引入了不调用父`__construct`,或调用父`__construct`并删除构造函数参数的可能性.这可能会导致在布局xml更新中使用块的行为方式不一致. (6认同)