Magento Events - best practice

Events are things that occurred in the system that other components might be interested in knowing about. Events represent the essence of asynchronous communication. Decoupling, reusing, and speeding up code are some of the benefits of using Events.

Triggering event in magento from a class

namespace MyCompany\MyModule;

use Magento\Framework\Event\ManagerInterface as EventManager;

class MyClass
{
  /** @var EventManager */
  private $eventManager;

  /*
   * @param \Magento\Framework\Event\ManagerInterface as EventManager
   */
  public function __construct(EventManager $eventManager)
  {
    $this->eventManager = $eventManager;
  }

  public function process(): void
  {
    $eventData = 'some data';
    $this->eventManager->dispatch('my_custom_event', ['payload' => $eventData]);
  }
}

The following code triggers event my_custom_event with parameter payload as the data passed along with it. You can create an observer to listen to this event and do other processing on your application.

what clients say about us

Client testimonials

Our sites look great and run smoothly. Thanks for all your hard work and patience in getting us to where we are today.

contact us

Contact Us

If you have questions or want us to send you a quote for project please email us.

latest news

Articles

PHPUnit mock magic functions
Learn more about PHPUnit Partial Mock.