How to Create Preference in Magento 2

Written by Mahesh Makwana

Mar 23, 2021

How to Create Preference in Magento 2

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 in magento 2

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.

Mahesh Makwana

Author

We can help you with

  • Dedicated Team
  • Setup Extended Team
  • Product Development
  • Custom App Development

Schedule a Developer Interview And Get 7 Days Risk-Free Trial

Fill out This Form and one of Our Technical Experts will Contact you Within 12 Hours.

    Google
    |

    4.8

    Google
    |

    4.8

    Google
    |

    4.9

    Google
    |

    4.8

    Google
    |

    4.9

    Copyright © 2024 DOLPHIN WEB SOLUTION. All rights reserved.

    TO TOP