【问题标题】:Where am i mistaken using Magento's observer pattern?我在哪里误用 Magento 的观察者模式?
【发布时间】:2012-01-26 11:40:04
【问题描述】:

我阅读了很多关于为 Magento 创建自定义模块的文档。

第一次尝试,我使用Module Creator创建了模块结构,这是我在/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> 

我的/app/etc/modules/Test_MyModule.xml 文件:

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

这是我的/app/code/local/Test/MyModule/Model/Observer.php

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

.. 但是 Test_MyModule_Model_Observer::sendOrder() 函数从未被触发(我尝试在其中放入一个虚拟数据库记录器以查看该函数是否/何时执行)。

我知道模块本身已正确加载,因为在模块的 config.xml 中,它在主菜单中声明了一个新链接,并且该链接正确显示(在刷新 magento 的缓存之后),所以我猜问题是函数命名我在某处遗漏的约定……但是在哪里?

【问题讨论】:

    标签: magento magento-1.5 observer-pattern


    【解决方案1】:

    我可以看到您有两个相关的问题。您正在使用 Mage::getModel 接受的语法指定要使用的类,但是您 a.) 语法略有错误,b.) 似乎实际上并没有声明您的模型包含在哪里(除非您为了更简洁)。

    您需要将模型添加到全局节点中。

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

    testmodule 部分可以是您喜欢的任何内容,只要它对您的模块来说是独一无二的。观察者部分使用的类值将变为...

    <class>testmodule/observer</class>
    

    【讨论】:

    • 此外,我建议公共函数 sendOrder() 接受 $observer 参数,因此它将是公共函数 sendOrder($observer)
    • 不是严格要求,但你是对的,它肯定会增加更多的清晰度。
    • 工作就像一个魅力! @JevgeniSmirnov 是的,您是对的,在真正的函数中,我将使用观察者参数来执行函数需要执行的操作;我发布的功能只是一个例子;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    • 1970-01-01
    相关资源
    最近更新 更多