How To Override A Controller in Magento 2

While developing a website or creating custom modules in Magento 2, you may require to change the native features of the core files like a controller. It’s a good practice to override the core files instead of making changes directly to it. 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 Magento 2 controller easily.

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

Step 1: Defining New Module

In order to override the native features in Magento 2, you have to create a new extension. For that, create an XML file named module.xml like a file path given below to define the new module,

Sample File Path: 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 PHP file named registration.php like a file path given below,

Sample File Path: app/code/MyModule/OverrideController/registration.php


Step 2: Setting Preference in di.xml

In Magento 2, to override the controller file you must use preference. For that, create an XML file named di.xml like a file path given below to refer the overriding class,

Sample File Path: 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 the core class Magento\Catalog\Controller\Product\View.

Step 3: Overriding Controller Class

Finally, create a PHP file named View.php like a file path given below to define the overriding controller class,

Sample File Path: 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 *