Events(事件)和observers(观察者)
概述
使用 Events(事件)和observers(观察者)是一个扩展Magento功能的主要途径。Events(事件)和observers(观察者)在Magento 2实现是基于发布/订阅模式。使用Events(事件)和observers(观察者你可以在一个特定的Magento事件甚至自定义事件运行自定义代码。
事件
当某些动作被触发时,模块会发送事件。除了它自己的事件,Magento允许你创建自己的事件,可以派遣你的代码。当事件被发送时,它可以将数据传递给配置为观看该事件的任何观察者。
调度事件
namespace MyCompany\MyModule ;
use Magento\Framework\Event\ObserverInterface ;
class MyClass {
/**
* @var EventManager
*/
private $eventManager ;
public function __construct ( \Magento\Framework\Event\Manager $eventManager ){
$this -> eventManager = $eventManager ;
}
public function something (){
$eventData = null ;
// Code...
$this -> eventManager -> dispatch ( 'my_module_event_before' );
// More code that sets $eventData...
$this -> eventManager -> dispatch ( 'my_module_event_after' ,[ 'myEventData' => $eventData ]);
}
}
Observers(观察者)
观察家都是某种类型的Magento类能够影响的一般行为,表现,或更改业务逻辑。当事件被配置为监视的事件被事件管理器发送时,执行。
创建一个观测器
namespace MyCompany\MyModule\Observer ;
use Magento\Framework\Event\ObserverInterface ;
class MyObserver implements ObserverInterface
{
public function __construct ()
{
//Observer initialization code...
//You can use 依赖注入 to get any class this observer may need.
}
public function execute ( \Magento\Framework\Event\Observer $observer )
{
//Observer execution code...
}
}
One of the more powerful feature of observers is that they are able to use parameters passed into the event when it was dispatched. Below is an example of an observer obtaining data passed in when the event was dispatched.
namespace MyCompany\MyModule\Observer ;
use Magento\Framework\Event\ObserverInterface ;
class AnotherObserver implements ObserverInterface
{
public function __construct ()
{
//Observer initialization code...
//You can use 依赖注入 to get any class this observer may need.
}
public function execute ( \Magento\Framework\Event\Observer $observer )
{
$myEventData = $observer -> getData ( 'myEventData' );
//Additional observer execution code...
}
}
订阅事件
<?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= "my_module_event_before" >
<observer name= "myObserverName" instance= "MyCompany\MyModule\Observer\MyObserver" />
</event>
<event name= "my_module_event_after" >
<observer name= "myObserverName" instance= "MyCompany\MyModule\Observer\AnotherObserver" />
</event>
</config>
推荐阅读