Observer

With observers you can hook in on events fired by Magento or other third party modules. For creating an observer we need the event name and the scope:

  • Event name: Name of event you want to observe, example: catalog_product_save_after
  • Scope: For which scope the observer is active.
    • All: Observer is always active
    • Frontend: Observer is only active in the frontend of Magento.
    • Backend: Observer is only active in the admin panel of Magento.

Some events:

  • sales_order_place_before
  • sales_order_place_after
  • checkout_cart_product_add_after
  • checkout_cart_update_items_before
  • checkout_cart_save_before
  • catalog_product_get_final_price

Use the snippet in the Magento 2 module creator.

Files

etc/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="Test">
		<observer name="mage2gen_module_observer_test_Test" instance="Mage2Gen\Module\Observer\Test"/>
	</event>
</config>

Observer/Test.php

<?php
declare(strict_types=1);

namespace Mage2Gen\Module\Observer;

class Test implements \Magento\Framework\Event\ObserverInterface
{

    /**
     * Execute observer
     *
     * @param \Magento\Framework\Event\Observer $observer
     * @return void
     */
    public function execute(
        \Magento\Framework\Event\Observer $observer
    ) {
        //Your observer code
    }
}