events

<?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>
<?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:

$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

发表评论

电子邮件地址不会被公开。 必填项已用*标注