通过 getModel 调用函数 vs 通过对象直接调用

Calling function through getModel vs direct calling through object

在 Magento 中,如果我们想从模型中调用函数,那么我们更喜欢使用 Mage::getModel('moduleName/className')->函数名();但我们也可以直接使用 Namespace_ModuleName_Model_ClassName::FunctionName(); 来实现它。

我知道根据 Magento 我们必须使用 getModel 但我检查过有人使用直接 Php 方法调用函数并说 "This was preferred against the Mage::getModel way due to the fact that we won’t need to instantiate the whole model for one simple array. If we would use the Mage::getModel expression, the model will first need to instantiate (executing its constructor) before executing the “functionname” method, which only returns an array and does not have complex logic. This way it’s way faster and it also limit the logic executed to return the steps array."

请建议哪种使用方法更可取,advantage/disadvantage 使用直接调用函数。

如果您正在调用这样的方法:Namespace_ModuleName_Model_ClassName::FunctionName(),那么您假设这是一个静态方法。只能这样调用静态方法。

a good write-up on when to use static methods 见此处。这个想法是静态方法是无状态的,不需要对象的上下文来 运行。在这种情况下,确实不需要实例化对象,因为静态方法不应该调用实例方法,所以它们不会使用 $this 关键字。

Magento 中,情况有点不同,因为 getModel 为您提供了一个非常重要的功能:class 重写。

如果您这样做 Mage::getModel('moduleName/className'),Magento 使用 class 重写 config.xml 将此名称解析为 PHP class。这意味着您可以在您的 local 命名空间中重写一个核心或社区 class,Magento 将在代码的任何地方使用您的 class,代替旧的。

牢记这一点,您可以很容易地看到使用静态方法并直接调用它们的缺点:您将无法重写它们!

如果您想在静态方法中修改代码,您唯一的 'clean' 解决方案是将整个文件复制到 app/code/local/Original/Module;多次这样做会使升级变得困难。