How to apply observers, preferences, and plugins correctly in Magento 2

Observers, preferences, and plugins are all powerful tools in Magento 2 that can be used to modify and extend the behavior of the platform. Here’s a brief overview of each, along with an example of how to use them:

  1. Observers: Observers are used to listen for specific events that occur in Magento and execute custom code in response to those events. To create an observer, you need to define an event in Magento’s XML configuration and then create a PHP class that will listen for that event. Here’s an example:

Let’s say you want to modify the behavior of the checkout process when a customer submits their order. You could create an observer that listens for the sales_order_place_after event, which is triggered after an order has been successfully placed. To create this observer, you would define the event in app/code/Vendor/Module/etc/events.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="sales_order_place_after">
        <observer name="my_custom_observer" instance="Vendor\Module\Observer\CustomObserver" />
    </event>
</config>

Then, you would create a PHP class CustomObserver.php in app/code/Vendor/Module/Observer that implements the Magento\Framework\Event\ObserverInterface interface:

namespace Vendor\Module\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

class CustomObserver implements ObserverInterface
{
    public function execute(Observer $observer)
    {
        // Your custom code here
    }
}

In this class, you can write any custom code that you want to execute when the sales_order_place_after event is triggered.

  1. Preferences: Preferences are used to override the default behavior of Magento classes with your own custom implementation. To create a preference, you need to define the class you want to override in Magento’s XML configuration and then create a new class that extends the original class. Here’s an example:

Let’s say you want to modify the behavior of the Magento\Catalog\Model\Product class to add a custom method. You could create a preference that overrides this class with your own custom implementation. To create this preference, you would define the class in app/code/Vendor/Module/etc/di.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Model\Product" type="Vendor\Module\Model\CustomProduct" />
</config>

Then, you would create a new PHP class CustomProduct.php in app/code/Vendor/Module/Model that extends the original Magento\Catalog\Model\Product class:

namespace Vendor\Module\Model;

use Magento\Catalog\Model\Product as MagentoProduct;

class CustomProduct extends MagentoProduct
{
    public function myCustomMethod()
    {
        // Your custom code here
    }
}

In this class, you can write any custom methods or override any existing methods from the original Magento\Catalog\Model\Product class.

  1. Plugins: Plugins, also known as interceptors, are used to modify the behavior of public methods in Magento classes without modifying the original class code. To create a plugin, you need to define the class and method you want to modify in Magento’s XML configuration and then create a PHP class that intercepts the method call. Here’s an example:

Let’s say you want to modify the behavior of the Magento\Checkout\Block\Cart\Item\Renderer class to add some custom HTML to the product name. You could create a plugin that intercepts the toHtml method in this class and adds your custom HTML. To create this plugin, you would define the class and method in app/code/Vendor/Module/etc/di.xml:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <type name="Magento\Checkout\Block\Cart\Item\Renderer">
        <plugin name="my_custom_plugin" type="Vendor\Module\Plugin\CustomPlugin" sortOrder="10" disabled="false" />
    </type>
</config>

Then, you would create a PHP class CustomPlugin.php in app/code/Vendor/Module/Plugin that implements the Magento\Framework\Interception\InterceptorInterface interface:

namespace Vendor\Module\Plugin;

use Magento\Checkout\Block\Cart\Item\Renderer as MagentoRenderer;

class CustomPlugin
{
    public function aroundToHtml(MagentoRenderer $subject, callable $proceed)
    {
        // Your custom code here to modify the product name HTML
        $result = $proceed();
        // Your custom code here to modify the product name HTML
        return $result;
    }
}

In this class, you can modify the behavior of the toHtml method by wrapping it with your own code using the around plugin method. The first parameter is the original class instance, and the second parameter is a callable function that represents the original method. Inside the around method, you can add your custom code before and after the original method call.

Note: The sortOrder attribute in the XML configuration determines the order in which plugins are executed. Lower numbers are executed first.

Additionally, the disabled attribute can be set to true to disable the plugin without removing it from the configuration.

So, in the CustomPlugin class, you can write any custom code that you want to execute before or after the toHtml method is called on an instance of the Magento\Checkout\Block\Cart\Item\Renderer class. The aroundToHtml method provides the ability to modify the input parameters and/or the return value of the original method.

In summary, observers, preferences, and plugins are powerful tools in Magento 2 that can be used to modify and extend the behavior of the platform. Observers allow you to listen for specific events and execute custom code in response, preferences allow you to override the default behavior of Magento classes with your own custom implementation, and plugins allow you to modify the behavior of public methods in Magento classes without modifying the original class code. By using these tools correctly, you can create highly customizable and extensible Magento modules that meet the needs of your clients or business.

Scroll to Top