{ Hello Magento 2 }

解决 Magento 2 应用问题,更注重深度挖掘。(ง •̀_•́)ง

0%

events

1
2
3
4
5
6
<?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="controller_custom_event">
<observer name="doA" instance="VendorName\TestModule\Observer\doA" />
</event>
</config>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
namespace VendorName\TestModule\Observer;

class doA implements \Magento\Framework\Event\ObserverInterface
{
public function execute(\Magento\Framework\Event\Observer $observer)
{
$writer = new \Zend\Log\Writer\Stream(BP . '/var/log/layout_block.xml');
$logger = new \Zend\Log\Logger();
$logger->addWriter($writer);
$logger->info('doA');
$logger->info(get_class($observer));
$logger->info(print_r($observer->getData('my_event_data'), true));
$logger->info(print_r($observer->getMyEventData(), true));

}
}

Dispatching events:

1
2
3
4
$eventData = 'ssss';
/* @param \Magento\Framework\Event\Manager */
$eventManger = $this->_objectManager->get('\Magento\Framework\Event\ManagerInterface');
$eventManger->dispatch('controller_custom_event', ['my_event_data' => $eventData]);

Best practices

  • Make your observer efficient
  • Do not include business logic
  • Declare observer in the appropriate scope
  • Avoid cyclical event loops
  • Do not rely on invocation order

References

Observers Best Practices