How To Create Preference in Magento 2

Hello Everyone,

In this blog, we will learn about how to Create Preference in Magento 2.

Without wasting your time, let us guide you straight away. Follow the easy step given below to Create Preference in Magento 2.

What is Preference?

Magento Preference uses Object Manager to extend the default implementation. You can use Preference to  implement some interface or rewrite/override existing classes and methods.

We can use preference to override or rewrite the Block, Model, Helper, Controller.

STEPS FOR CREATE PREFERENCE IN MAGENTO 2

Step 1: Create di.xml file

app/code/Vendor/Extension/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="Vendor\Extension\Model\NameChange" />
</config>

Step 2: Create NameChange.php file

app/code/Vendor/Extension/Model/NameChange.php

<?php
namespace Vendor\Extension\Model;

class NameChange extends \Magento\Catalog\Model\Product
{
    public function getName()
    {
        return "Magecurious";
    }
}

Using above code all Product Name should change to Magecurious.

Step 3: Finally run the below commands

$ php bin/magento setup:di:compile
$ php bin/magento cache:clean
$ php bin/magento cache:flush

Step 4: Output:

Final Thoughts:

So this was the easiest way which we have told you in this blog. This is how you can Create Preference in Magento 2. Hope you liked the blog.

So quickly go to the comment box and tell me how you like this blog?

Stay tuned with us on our site to get new updates of Magento.

Thanks for reading and visiting our site.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

Leave a Reply

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