如何在 Magento 2 中使用事件和观察者
How to use events and observers in Magento 2
我想通过挂钩 Magento 事件来跟踪 Magento 商店数据。我是 Magento2 的新手,所以我不知道挂钩事件以及在哪里调用观察者。我想知道如何调用我们可以调用哪个目录的事件。可以使用什么层次结构?如何知道事件的名称?
您可以在手册中找到有关事件和观察者的非常基本的信息,请在此处查看:https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html
创建事件文件:events.xml
文件: app/code/Vendor_Name/Module_Name/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_add_product_complete">
<observer name="observername" instance="Vendor_Name\Module_Name\Observer\ObserverClass" />
</event>
</config>
创建观察者class
文件: app/code/Vendor_Name/Module_Name/Observer/ObserverClass.php
<?php
namespace Vendor_Name\Module_Name\Observer;
class ObserverClass implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
//Your code to run when event is fired.
return 'Event fired';
}
}
在上面的例子中,每当触发事件“checkout_cart_add_product_complete”时,Observer class 中的代码将被执行。
要获取 Magento 2 中可用的事件列表,您可以访问:Link
谢谢,希望对您有所帮助。如果您有任何疑问或问题,请随时在评论中提问。
我想通过挂钩 Magento 事件来跟踪 Magento 商店数据。我是 Magento2 的新手,所以我不知道挂钩事件以及在哪里调用观察者。我想知道如何调用我们可以调用哪个目录的事件。可以使用什么层次结构?如何知道事件的名称?
您可以在手册中找到有关事件和观察者的非常基本的信息,请在此处查看:https://devdocs.magento.com/guides/v2.3/extension-dev-guide/events-and-observers.html
创建事件文件:events.xml
文件: app/code/Vendor_Name/Module_Name/etc/frontend/events.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
<event name="checkout_cart_add_product_complete">
<observer name="observername" instance="Vendor_Name\Module_Name\Observer\ObserverClass" />
</event>
</config>
创建观察者class
文件: app/code/Vendor_Name/Module_Name/Observer/ObserverClass.php
<?php
namespace Vendor_Name\Module_Name\Observer;
class ObserverClass implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
//Your code to run when event is fired.
return 'Event fired';
}
}
在上面的例子中,每当触发事件“checkout_cart_add_product_complete”时,Observer class 中的代码将被执行。
要获取 Magento 2 中可用的事件列表,您可以访问:Link
谢谢,希望对您有所帮助。如果您有任何疑问或问题,请随时在评论中提问。