Magento 2 : Override Php Class Functionality.

There are multiple ways to override a core functionality of PHP class in Magento 2 i.e preference and plugins are the top ones.

In this one, we will work with preference to override the core functionality. With Preference, you can extend a core class. Preference can be used to rewrite functions. When we declare or create a Preference, our new class is expected to be a complete implementation of the class that we want to override.

How to use Preference to override a core class in Magento 2?

The first thing that we want to Make sure of is to register the new module to test it before, we will practice on this module. In this example, We will change the Product Name by using Preference.
We can use preferences in Magento 2 to implement some interfaces or to rewrite/override the existing PHP classes and their methods

In the first step, we need to create a new file di.xml in app/code/GM/Module/etc and add the following codes to it

<?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="Magento\Catalog\Model\Product" type="Gm\Module\Model\Product"/>
</config>

In the above codes, the “for” attribute is where we place the path of the core class while the path of the class which will override is placed in the “type” attribute.

Next step, let’s create file Product.php in GM\Module\Model and add the below codes:

<?php

namespace Gm\Module\Model;
class Product extends \Magento\Catalog\Model\Product
{
    public function getName()
    {
        $changeNamebyPreference = $this->_getData('name') . ' modified by gm Module';
        return $changeNamebyPreference;
    }
}

Remember that class Product has to extend the core class defined in file di.xml. To change the name of all products, you need to declare the getName() method in your class. Use this code: $this->_getData(‘name’) to get the original product name, and you can add conditions or business logic to process it. The above codes are concatenating the original product name with the ‘ modified by gm Module’ string. Method getName() must return a value like its parent. 

When you’ve done this, clean the cache and go to product view, and you will see the change.

Leave a Comment

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