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 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)