Today we learn how to use Preference in Magento 2. At development time we need to rewrite some files, Preference helps us to achieve this.
Preference is used by the Object Manager to indicate the default implementation. You can use it to rewrite a class from another module to point at the implementation, which will cause the class to be used globally. If you want to override a public or protected method from a core class, utilize the preference from di.xml to achieve it. The preference node specifies the default implementation.
We can use the preference to override or rewrite the block, model, helper, controller. We can also rewrite custom module files. We define preference into app/code/VendoreName/ModuleName/etc/di.xml
Example of overriding a method from a core file. We rewrite the getName() function of class Magento\Catalog\Model\Product.
app/code/Dolphin/PreferenceDemo/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="Dolphin\PreferenceDemo\Model\Product" /> </config>
app/code/Dolphin/PreferenceDemo/Model/Product.php
<?php namespace Dolphin\PreferenceDemo\Model; class Product extends \Magento\Catalog\Model\Product { public function getName() { return "Preference Demo"; } }
Output: All product names are “Preference Demo” in the frontend.
Preference method is a powerful way to configure Magento’s core functionality. Sometimes, it might be too heavy-handed. The disadvantage of using preferences is that it can cause conflicts if multiple classes extend the same original class. Under some circumstances, you may want Magento’s default class selection to remain in place.
Preference is commonly used in Magento 2 development.
I hope this helps you. For any doubts regarding this topic, please write your doubts in the comments section.