Why model overriding does not work

I just met a case when overriding a module in Magento 1.x didn’t work. After some digging it has turned out that it will work only when the slashed notation of class naming is used. I won’t write down the steps to create a new extension, how to write a class or where to put files, because this article is about how to correctly override a model.

Example, when in the code it is used:

$validator = Mage:getModel("core/url_validator");

then you will be able to override it from your own module, by defining in config.xml:

<global>
    <modules>
        <core>
            <rewrite>
                <url_validator>Foo_Model_Bar_Checker</url_validator>
            </rewrite>
        </core>
    </modules>
</global>

However, if the code would use:

$validator = Mage::getModel("Mage_Core_Model_Url_Validator");

then it would be useless your efforts to override it. Why? The answer is quite obvious. Just take a look at Mage_Core_Model_Config:

public function getModelClassName($modelClass)
{
    $modelClass = trim($modelClass);
    if (strpos($modelClass, '/')===false) {
        return $modelClass;
    }
    return $this->getGroupedClassName('model', $modelClass);
}

When you are using the full class name notation, then it will just return it back. But when using Mage::getModel with slashes in the argument, then it will start parsing the config.xml files after possible rewrites.

It is up to you how you want to declare your models, maybe you want to make harder for others to override your code, then you can always specify the full class name. Or maybe you want your code to be faster by skipping a lot of config.xml parsing, that is also good. Otherwise just use the slashed notation.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.