In this blog, we will be discussing about the Preference of protected type methods.
But before that we should know about the Preferences:.
https://webkul.com/blog/plugins-observers-and-preference-in-magento2/
The Magento2 provides us with these options to modify the code to large extent but we do need to know about the strengths and the weakness of the same so that we can use them in the most appropriate places when required.
Using the Preference, we tell the Magento Object Manager to inter-change one class to another. The Object Manager checks for preference class entry for a class while creating its new object. In case, an entry is found while injecting, it will swap the object from the original class to the parent class.
The major problem while doing this is this will actually create a parallel flow of the code for execution and the original code will never be executed. This is something that we must avoid as changing the flow of the code, mostly returns in logical errors or bugs at certain levels.
Till now we used to make the preference only for public functions but we can create the preference for protected functions.
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 type methods.
Be the first to comment.