Magento 2.x Preference

Preference is used to override or rewrite existing / custom classes (Controller, Block & Helper). Preference using Dependency Injection to override or rewrite classes.

How To Define Preference : Preference is defined inside di.xml

Path : app/code/VendorName/ModuleName/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">

<preference for="Class Which Override" type="Custom Class By Which Override" />

    </config>

Overriding (By Preference in di.xml) a method is not recommended because it can cause conflicts in the system and increase the complexity to upgrade.

Always try to user other extensibility options, such as event observers and plugins, when possible.

Leave a Reply

Your email address will not be published. Required fields are marked *