Controller Override in Magento 2
Nidhi Arora
- 5 years
- 110 views

Today, we’re going to explain how to override controller in Magento 2 and hope you are already familiar with controller & its functionality. Controller basically stands behind the process of handling incoming requests and it plays a significant role in Magento 2 routing implementation. Controller overriding is mainly required while working on custom modules in Magento 2 and you need to work on overriding core module files.
By following the simple steps as mentioned below, you can easily override the controller in Magento 2 and we hope that you can grab that “Ah-ha!” moment. Or at the very least you’ll say, “That’s very easy.”
Step1)
Create di.xml file in app/code/<VendorName>/<ModuleName>/etc <?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\Checkout\Controller\Cart\Add" type="<VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add" /> </config> Code Explanation <VendorName>\<ModuleName>\Controller\Rewrite\Cart\Add is used to override Magento\Checkout\Controller\Cart\Add
Step2)
Define an overriding controller class
Create Add.php in app/code/<VendorName>/<ModuleName>/Controller/Rewrite/Cart/ <?php namespace <VendorName>\<ModuleName>\Controller\Rewrite\Cart; class Add extends \Magento\Checkout\Controller\Cart\Add { public function execute() { // perform action } }