How To Override A Controller in Magento 2

While developing a Magento 2 website or creating custom modules in Magento 2, it’s very important to override core module files (i.e, controller) instead of making changes to it directly. Overriding the controller in Magento 2 is very easy and it gives you the flexibility to change the core functionality as per your requirement.

By following the below steps you can override the core controller easily.

  • Defining a new module
  • Setting preference in di.xml
  • Defining an overriding controller class

Step 1: Defining a new module

Create a module.xml file in the below file path to define the new module,

File Path: <Magento_2_Root>/app/code/MyModule/OverrideController/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="MyModule_OverrideController" setup_version="1.0.0">

Next, create a registration.php file in the below file path,

File Path: <Magento_2_Root>/app/code/MyModule/OverrideController/registration.php


Step 2: Setting preference in di.xml

Create a di.xml file in the below file path to refer the overriding class

File Path: <Magento_2_Root>/app/code/MyModule/OverrideController/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Controller\Product\View" type="MyModule\OverrideController\Controller\Product\View" />

Here, “MyModule\OverrideController\Controller\Product\View” will be used to override “Magento\Catalog\Controller\Product\View”.

Step 3: Defining an overriding controller class

Create View.php file in the below file path to define the overriding controller class

File Path: <Magento_2_Root>/app/code/MyModule/OverrideController/Controller/Product/View.php

namespace MyModule\OverrideController\Controller\Product;

class View extends \Magento\Catalog\Controller\Product\View
    public function execute()
        // Do something here
        $this->messageManager->addSuccess('Message From OverrideController.');

        return parent::execute();

Hope this helps.

Leave a Reply

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