开发者

conditionally overriding/rewriting a class in magento

I know that I can override/rewrite a model class from my module using the following syntax in the config.xml for my module.:

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

But what if I want this to be conditional (e.g. based on some setting in my modules adminhtml configuration section?)

Is there any syntax for this?

开发者_JS百科

Alternatively is there a way for my rewritten class to get to the class as it was before my rewrite? (to allow it to call its "predecessor".


There's no built in configuration option that will allow you to conditionally rewrite a class like this.

However, a rewritten class is just an extended class, so all standard OOP rules apply, including using parent:: So something like

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
    }
}

Finally, although I've never tried it, you should be able to get a reference to to parsed config options with

$config->Mage::getConfig();

And then manually set or unset your rewrite option using its setOptions method.


There are a couple of good suggestions in this discussion: What is the best way to limit a modules functionality by store or website

In particular, this answer has a short and sweet technique that can be used for more than just store-conditionality.


An approach like parent::theMethodIRewrote($param, $options) is not always usable, so try the following quite simple solution:

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 ... */

    }

}

In my case (magento 1.6.0.0,php 5.3) it seems to be working.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜