【问题标题】:conditionally overriding/rewriting a class in magento有条件地覆盖/重写magento中的类
【发布时间】:2011-01-18 10:07:05
【问题描述】:

我知道我可以使用模块的 config.xml 中的以下语法覆盖/重写模块中的模型类。:

<config>
    <global>
        <models>
            <moduletooverride>
                <rewrite>
                    <modeltooverride>Mycompany_Mymodule_Model_Myfolder_Myclass</customer>
                </rewrite>
            </moduletooverride>
         </models>
     </global>
</config>

但如果我希望这是有条件的(例如,基于我的模块 adminhtml 配置部分中的某些设置?)

这有什么语法吗?

或者,有没有办法让我重写的课程像我重写之前一样进入课程? (允许它调用它的“前身”。

【问题讨论】:

    标签: php xml magento magento-1.4


    【解决方案1】:

    没有内置的配置选项允许您有条件地重写这样的类。

    然而,重写的类只是一个扩展类,所以所有标准的 OOP 规则都适用,包括使用 parent:: 之类的东西

    class My_Rewritten_Class extends Class_I_Rewrote
    {
    
        public function theMethodIRewrote($param, $options)
        {
            $original_results = parent::theMethodIRewrote($param, $options);
            if(!Mage::getStoreConfigFlag('path/to_my/on_or_off_flag'))
            {
                return $original_results
            }
    
            //continue with the rewrite
        }
    }
    

    最后,虽然我从未尝试过,但您应该可以使用

    获得对已解析配置选项的引用
    $config->Mage::getConfig();
    

    然后使用 setOptions 方法手动设置或取消设置重写选项。

    【讨论】:

    • 但是这个(第一个建议)并没有关闭重写,因为如果你有两个类试图重写同一个核心类,它不允许我的类优雅地让开并让重写其他类的仍然发生。它将禁用我自己的功能以及第二类的功能,以支持原始的 magento 行为。
    • 至于操作配置,我觉得即使这在某些时候会起作用,它也将取决于读取配置文件的顺序,并且不会提供一个万无一失的解决方案。
    • 以上均为准确说法。
    • 确实感觉有点老套,但效果很好。如果商店配置认为重写活动,只执行父函数不是更好吗?这样,如果 Mage::getStoreConfigFlag('path/to_my/on_or_off_flag') 返回 true,就不会不必要地执行该函数。
    【解决方案2】:

    在这个讨论中有几个很好的建议:What is the best way to limit a modules functionality by store or website

    特别是,this answer 有一个简短而实用的技术,不仅可以用于存储条件。

    【讨论】:

      【解决方案3】:

      类似的方法 parent::theMethodIRewrote($param, $options) 并不总是可用,因此请尝试以下非常简单的解决方案:

      if (!Mage::helper('mymodule')->isEnabled()){
      
          class My_Rewritten_Class extends Class_I_Rewrote{} //empty body - nothing rewritten
      
      }else{
      
          class My_Rewritten_Class extends Class_I_Rewrote{
      
              public function theMethodIRewrote($param, $options){
                    /* method body ... */
              }
      
              /* other methods ... */
      
          }
      
      }
      

      在我的情况下(magento 1.6.0.0,php 5.3)它似乎正在工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-15
        • 2023-02-04
        • 2015-09-21
        相关资源
        最近更新 更多