在 Magento 中设置观察者的正确方法是什么?

2021-12-19 00:00:00 php magento zend-framework

我想在 Magento 中设置一个观察者,在订单状态发生变化时执行一个操作.

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

我熟悉创建模块的过程.我想了解的是需要在模块 config.xml 中放置什么,以及需要创建的类和/或方法的命名约定是什么.

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.

推荐答案

我在任何地方都没有看到事件名称,但我会在此处发布一般情况:

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

假设:您已经设置了一个模块,并且从 Yourmodule/Model 目录中正确加载了模型..

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

在您模块的 config.xml 文件中:

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>

创建一个 %yourmodule%/Model/Observer.php 文件,内容如下:

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

实际上,您可以在观察者中随意命名方法,但模式似乎是将类本身命名为观察者.它使用普通模型加载(例如 yourmodule/observer 映射到 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!

谢谢,乔

相关文章