:::: MENU ::::

Magento 2 overriding or Rewriting controller

Magento 2 overriding or Rewriting controller

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 override core blocks. In start we are overriding or rewriting controller. We are just checking our rewrite is working or not. You can modify the blocks as you want by 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 controller

A Controller has one or more files in Controller folder of module, it includes actions of class which contain execute() method. There are 2 different controllers, they are frontend controller and backend controller.Now we start to overriding or rewriting core Product controller. The controller we are overriding is Product View controller. Magento 2 use controller for category product listing.

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\Controller\Product\View" type="QaisarSatti\HelloWorld\Controller\Rewrite \Product\View" />
</config>

Step 2
The step2 to overriding or rewriting Magento 2 controller is to create a View.php controller file in the following directory QaisarSatti\HelloWorld\Controller\Rewrite \Product\

<?php
/**
* Catalog Product Rewrite controller
*
* @category QaisarSatti
* @package QaisarSatti_HelloWorld
* @author Muhammad Qaisar Satti
*
*/

namespace QaisarSatti\HelloWorld\Controller\Rewrite\Product;
class View extends \Magento\Catalog\Controller\Product\View
{
public function execute() {


echo "Controller Rewrite Working"; die();
  }
}

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

Author: Qaisar Satti
Category: Magento 2
Last Modified: July 12, 2018


2 Comments

So, what do you think ?