0

When creating an observer you add your model to config.xml like ...

<models>
    <some_name>
        <class>My_Module_Model</class>
    </some_name>
</models>

When adding the event part you can do this

<observers>
    <some_alias>
        <class>some_name/observer</class>
        <method>someMethod</method>
    </some_alias>
</observers>

Or use full class name like

<observers>
    <some_alias>
        <class>My_Module_Model_Observer</class>
        <method>someMethod</method>
    </some_alias>
</observers>

Whats the difference and why should I prefer one over the other?

3

Thanks Sohel Rana, for pointing to $this->getGroupedClassName('model', $modelClass);

This makes the difference.

Most important lines for this question are:

// First - check maybe the entity class was rewritten
$className = null;
if (isset($config->rewrite->$class)) {
    $className = (string)$config->rewrite->$class;
} else {

If using full class name, rewrites of the related model have no effect. It will load the class that is declared. If using some_name/observer you can rewrite Some_Modules_Model_Observer and the new class is used. Think it's better to use second approach.

  • 1
    Absolutely. You can still rewrite observers in both cases by overriding observers/some_alias/class in config.xml of an own module that depends on the original one. But it's better to keep the possibility to rewrite the observer class itself. – Fabian Schmengler Jul 31 '17 at 17:21
1

There are no big difference when Magento create an object of class tag. Open app/code/core/Mage/Core/Model/Config.php


/**
 * Retrieve module class name
 *
 * @param   sting $modelClass
 * @return  string
 */
public function getModelClassName($modelClass)
{
    $modelClass = trim($modelClass);
    if (strpos($modelClass, '/')===false) {
        return $modelClass;
    }
    return $this->getGroupedClassName('model', $modelClass);
}

Check line if (strpos($modelClass, '/')===false) {

If you pass My_Module_Model_Observer type of name then magento return this without anything.

If you pass some_name/observer then return $this->getGroupedClassName('model', $modelClass); this code create a actual class and return.

So both ways are acceptable and magento standard.

  • Thanks for pointing to getGroupedClassName() :) – sv3n Jul 24 '17 at 14:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.