我见过几种不同的方法来获得一个特定的 helper
,我希望有人可以解释每种方法的优缺点。例如,在 template/checkout/cart/sidebar/default.phtml
,您将看到两个 $this->helper('checkout')
和 Mage::helper('checkout')
.在同一个模板中使用这两种不同的方法是否有充分的理由?
以下是我可以在 Magento 中找到的所有不同的帮助方法:
abstract class Mage_Core_Block_Abstract extends Varien_Object
{
…
/**
* Return block helper
*
* @param string $type
* @return Mage_Core_Block_Abstract
*/
public function getHelper($type)
{
return $this->getLayout()->getBlockSingleton($type);
}
/**
* Returns helper object
*
* @param string $name
* @return Mage_Core_Block_Abstract
*/
public function helper($name)
{
if ($this->getLayout()) {
return $this->getLayout()->helper($name);
}
return Mage::helper($name);
}
…
}
class Mage_Core_Model_Layout extends Varien_Simplexml_Config
{
…
/**
* Enter description here...
*
* @param string $type
* @return Mage_Core_Helper_Abstract
*/
public function getBlockSingleton($type)
{
if (!isset($this->_helpers[$type])) {
$className = Mage::getConfig()->getBlockClassName($type);
if (!$className) {
Mage::throwException(Mage::helper('core')->__('Invalid block type: %s', $type));
}
$helper = new $className();
if ($helper) {
if ($helper instanceof Mage_Core_Block_Abstract) {
$helper->setLayout($this);
}
$this->_helpers[$type] = $helper;
}
}
return $this->_helpers[$type];
}
/**
* Retrieve helper object
*
* @param string $name
* @return Mage_Core_Helper_Abstract
*/
public function helper($name)
{
$helper = Mage::helper($name);
if (!$helper) {
return false;
}
return $helper->setLayout($this);
}
…
}
最佳答案
Mage_Core_Block_Abstract::getHelper()
Mage_Core_Model_Layout::getBlockSingleton()
方法不返回 Magento 辅助对象,而是 Magento 对象类型 block 的实例。
我相信这是遗留代码,例如 Mage::getBlockSingleton()
方法已弃用。
在这两种情况下, block 实例都是从 Magento 类 ID 创建的。
方法getBlockSingleton()
将实例存储在 $_helpers
布局对象的属性,方法createBlock()
将其存储在 $_blocks
属性(property)。
仅来自 $_blocks
的 block 可以使用布局 XML 引用(和覆盖)数组。
方法getBlockSingleton()
如果你想要一个特定 block 类的实例,并且你想确保在 block 已经存在的情况下不要创建一个新的实例,那么它很有用。
通过 createBlock()
创建的实例达到(几乎)相同的效果您将需要以下代码:
public function alternativeGetBlockSingleton($classId)
{
foreach (Mage::app()->getLayout()->getAllBlocks() as $block)
{
if ($block->getType() == $classId)
{
return $block;
}
}
return $this->createBlock($classId);
}
Mage_Core_Block_Abstract::helper()
Mage_Core_Block_Abstract::helper()
方法返回 Magento 中通常称为助手的实例。调用
Mage::helper($name)
的唯一区别直接是布局对象被设置为助手实例上的属性。有人可能会争辩说,使用
$this->helper()
模板文件中的 Mage::helper()
更干净,因为它减少了对 Mage
的硬编码引用(以及依赖关系)的数量。类,但在 Magento 的情况下,该参数是徒劳的,因为每个模块都非常依赖 Mage
和一些 Mage_Core
反正上课。实际上,除了
Mage::helper()
更为常见和广为人知,其他开发人员阅读代码时不会感到困惑,这使其更易于维护。另一方面,Magento 是关于选择的,并且有很多方法来完成给定的任务。
关于magento - Magento 中不同的 *get helper* 方法有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9334502/