Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top