Search code examples
magentomagento-1.5observer-pattern

Where am i mistaken using Magento's observer pattern?


I read a lot of documentation about custom module creation for Magento.

For my fist try, i created the module structure using Module Creator, and this is the code i added in /app/code/local/Test/MyModule/etc/config.xml:

<?xml version="1.0"?>
<config>
    <modules>
        <Test_MyModule>
            <version>0.1.0</version>
        </Test_MyModule>
    </modules>
    <!-- frontend, admin, adminhtml -->
    <global>
        <!-- models, resources, blocks, helpers -->
        <events>
          <sales_order_place_before> <!-- event i need to catch -->
            <observers>
              <trigger_mymodule_placeorder> 
                <type>model</type>
                <class>test/mymodule/model_observer</class>
                <method>sendOrder</method>
              </trigger_mymodule_placeorder>
            </observers>
          </sales_order_place_before>
        </events>
    </global>
</config> 

My /app/etc/modules/Test_MyModule.xml file:

<?xml version="1.0"?>
<config>
    <modules>
        <Test_MyModule>
            <active>true</active>
            <codePool>local</codePool>
        </Test_MyModule>
    </modules>
</config> 

And this is my /app/code/local/Test/MyModule/Model/Observer.php:

<?php
class Test_MyModule_Model_Observer
{
    public function sendOrder()
    {
        // do something.
    }
}

.. but the Test_MyModule_Model_Observer::sendOrder() function is never triggered (i tryed putting inside it a dummy database logger to see if/when the function get executed).

I know the module itself is loaded correctly becose, in the module's config.xml, it declare a new link in main menu and the link get displayed correctly (after flushing magento's cache), so i guess the problem is the function naming convention that I am missing somewhere.. but where?


Solution

  • You have two issues that I can see, which are both related. You are specifying the class to use using the syntax that Mage::getModel accepts, but you are a.) slightly wrong in the syntax, b.) seemingly not actually declaring where you models are contained (unless you took it out in order to be more concise).

    You need to add your models into the global node.

    <models>
       <testmodule>
           <class>Test_MyModule_Model</class>
       </testmodule>
    <models>
    

    The testmodule part can be anything you like so long as it's unique for your module. The class value used in the observer part will then become...

    <class>testmodule/observer</class>