In this blog, we will discuss the preference for protected methods in Magento 2. But before that, let’s understand Preferences in Magento 2.
Magento 2 provides several ways to modify code, such as Plugins, Observers, and Preferences. To use them effectively, we must understand their strengths and weaknesses.
With Preference, the Object Manager replaces one class with another. It checks for a preference entry and swaps the original class with the preferred one when creating a new object.
The main drawback is that this creates a parallel execution flow, preventing the original code from running. This can lead to logical errors and unexpected bugs in the system.
Previously, Preferences were mainly used for public methods, but we can also create Preferences for protected methods. Let’s explore how this works! 🚀
We need to map the preference file in the di.xml file.
We have a Module named Demo Webkul_Demo.
File Path: app/code/Webkul/Demo/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Webkul\MobikulApi\Rewrite\Controller\Catalog\HomePageData" type="Webkul\Demo\Rewrite\Controller\Catalog\HomePageData" />
</config>
Preference file path: app/code/Webkul/Demo/Rewrite/Controller/Catalog/HomePageData.php
<?php
namespace Webkul\Demo\Rewrite\Controller\Catalog;
/**
* HomePageData Preference Action Class
*/
class HomePageData extends \Webkul\MobikulApi\Controller\Catalog\HomePageData
{
protected function methodName()
{
# your override code.
}
}
That’s all, now we can create the preference of public and protected both method types.
Be the first to comment.