We can rewrite controller with the help of router. Magento provides the attribute before/after to config the module sort order which define what module controller will be find first.
For example, if we want to rewrite the controller customer/account/login, we will define more route in the route.xml like this:
File: app/code/PHPCodez/First/etc/frontend/routes.xml
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd"> <router id="standard"> <route frontName="first" id="first"> <module name="PHPCodez_First"/> </route> <route id="customer"> <module name="PHPCodez_First" before="Magento_Customer" /> </route> </router> </config>
<?php namespace PHPCodez\First\Controller\Account; use Magento\Customer\Controller\Account; class Login extends \Magento\Customer\Controller\AbstractAccount { public function execute(){ die('PHPCodez Overridden Successfully. Cheers !!!! '); } }
And the controller file: app/code/PHPCodez/First/Controller/Account/Login.php
So the frontController will find the Login action in our module first, if it’s found, it will run and the Login action of Magento_Customer will not be run.
Now lean the cache and load the URL http://127.0.0.1/mage2/customer/account/login/ and the message ‘PHPCodez Overridden Successfully. Cheers !!!! ‘ will be displayed on the screen.
php bin/magento cache:flush