douheng8629 2016-02-26 07:23 采纳率: 100%
浏览 70
已采纳

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

In Magento if we want to call function from model then we prefer to use Mage::getModel('moduleName/className')->functionName(); but we can also achieve it directly using Namespace_ModuleName_Model_ClassName::FunctionName();

I know as per Magento we have to use getModel but I checked someone used direct Php method to call function and said "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."

Please suggest which will be the preferable way to use and advantage/disadvantage of using direct calling function.

  • 写回答

1条回答 默认 最新

  • dtz8044 2016-02-26 10:30
    关注

    If you are calling a method like this: Namespace_ModuleName_Model_ClassName::FunctionName(), then you are assuming this is a static method. Only static methods can be called like this.

    See here for a good write-up on when to use static methods. The idea is that static methods are stateless, and do not need the context of an object in order to run. In this case, it's true that you do not need to instantiate the object, as static methods should not call instance methods, so they don't make use of the $this keyword.

    In Magento, things are a bit different, in that getModel gives you a very important feature: class rewrites.

    If you do Mage::getModel('moduleName/className'), Magento resolves this name to a PHP class using it's class rewrites from config.xml. This means that you can rewrite a core or community class in your local namespace, and Magento will use your class everywhere in the code, in place of the old one.

    Keeping this in mind, you can easily see a drawback of using static methods and calling them directly: you will not be able to rewrite them!

    Your only 'clean' solution if you want to modify code in static methods is to copy the entire file in app/code/local/Original/Module; doing this many times will make upgrades difficult.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog