Tutorialsplane

Magento 2 Override Controller


Magento 2 Override Controller
It is very simple to override controller in Magento 2. Here in this article we are going to explain how you can override
Magento\Catalog\Controller\Product\View controller.

First of all you need to create di.xml inside module etc folder and you need to add the preferences & type inside this.


Magento 2 Override Controller Example

Let us understand this with real time example-

1. Create di.xml

Create di.xml and add the following code-

Example:

<?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\Controller\Product\View" type="Tutorialsplane\Helloworld\Controller\Rewrite\Product\View"></preference>
</config>

Create Controller

Now create View controller in your local module ie. View.php in Tutorialsplane\Helloworld\Controller\Rewrite\Product\ folder.

Example:

<?php namespace Tutorialsplane\Helloworld\Controller\Rewrite\Product;
 
    class View extends \Magento\Catalog\Controller\Product\View
    {
       
        public function execute()
        {
            // Do here whatever you want.
            return parent::execute();
        }
    }
</pre?>

All set, you are done. Now core controller \Magento\Catalog\Controller\Product\View is overriden by local module
controller Tutorialsplane\Helloworld\Controller\Rewrite\Product.