Magento 2 overriding Rewriting helper

Today we talk about Magento 2 overriding Rewriting helper. In our daily coding routine we need to customization with core files. For that we need to overriding or rewrite the core classes because modify the core classes is not good practice. If you modify the code classes when you update the new version your code will be loss. So today we learn how to Magento 2 overriding or Rewriting helper. In start we are overriding core Product helper. We are jut checking our rewrite is working or not. You can modify the helper as you want following this tutorial. But first you need to know How to create module in Magneto 2.For any suggestions & question, please feel free to drop a comment.

Overriding or Rewrite Magento 2 Helper

sometimes, you may want to add new classes or override different functions in your Magento 2 module. Therefore, Magento 2 came up with the Helpers that are the right entity to fulfill your needs. A Helper in Magento 2 is an object that contains practical methods.Now we start to overriding or rewriting core Product helper. The helper we are overriding is Product helper.
Step 1.

Create a di.xml file in a following directory QaisarSatti/HelloWorld/etc/

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Catalog\Helper\Product" type="QaisarSatti\HelloWorld\Helper\Rewrite\Product" />
</config>

Step 2
The step2 to overriding or rewriting Magento2 Helper is to create a Product.php helper file in the following directory QaisarSatti/HelloWorld/Helper/Rewrite/

<?php
/**
* Catalog Product overridingHelper
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Helper\Rewrite;
class Product extends \Magento\Catalog\Helper\Product
{
   public function __construct()
   {
     echo "Our Rewrite Working"; die();
   }
}

As following code you can rewrite or override any Magento 2 helper using the same method.

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

One thought on “Magento 2 overriding Rewriting helper

  1. I am magento 1 developer and your article is very help to understanding working magento 2. Rewriting class using dependency injection in article is very helpful.

Leave a Reply