What is the correct way to set up an observer in M

2019-01-26 01:57发布

问题:

I'd like to set up an observer in Magento that performs an action when the status of an order changes.

I'm familiar with process of creating modules. What I'm looking to understand is what needs to placed in the modules config.xml, and what is the naming convention for the classes and/or methods that need to be created.

回答1:

I don't see the event name anywhere, but I'll post the general case here:

Assumed: That you have a module set up, with models being loaded correctly from the Yourmodule/Model directory..

In your module's config.xml file:

<config>
    <global>
  <events>
   <full_event_name>
    <observers>
     <yourmodule>
      <type>singleton</type>
      <class>yourmodule/observer</class>
      <method>yourMethodName</method>
     </yourmodule>
    </observers>
   </full_event_name>
  </events>
 </global>
</config>

Create a file %yourmodule%/Model/Observer.php with the following contents:

<?php

class Yourmodule_Model_Observer {

    public function yourMethodName($event) {
        $data = $event->getData(); // this follows normal Magento data access

        // perform your action here
    }

}//class Yourmodule_Model_Observer

Really, you can name the method whatever you want within your observer, but the pattern seems to be to name the class itself Observer. It is loaded using normal model loading (e.g. yourmodule/observer maps to Yourmodule_Model_Observer). Hope that helps!

Thanks, Joe