Magento 2: What is Default Controller

If you are a Magento 1 developer, then it would be familiar that M1 has default controller (IndexController.php) and default method (indexAction()). This means, if there is nothing specified after a frontname, for example, a URL looks like www.example.com/frontname/ instead of traditional www.example.com/frontname/something1/something2, then M1 looks for default controller and default method inside the module where front name is defined as frontname.

Is this feature is available in Magento 2 ? The answer is Yes. Default Controller in M2 is Index.php which is defined at app/code/Namespace/Module/Controller/Index/Index.php and method is execute(). In fact all controller in M2 has a default controller method execute() which will be executed as per the URL.

To get more idea on this, let us look into an example. We have a module say, Rkt_HelloWorld. Let’s say we need to define a front name helloworld. To do this, we need to include this frontname inside router list.

File : app/code/Rkt/HelloWorld/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="helloworld" frontName="helloworld">
            <module name="Rkt_HelloWorld" />
        </route>
    </router>
</config>    

This tells to Magento that the module Rkt_HelloWorld will be responsible for processing all Urls that starts with helloworld. Now it’s time to define default controller for our module.

File : app/code/Rkt/HelloWorld/Controller/Index/Index.php

<?php
namespace Rkt\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        echo "<p>You Did It!</p>";
    }
}

See the controller path and definition of execute() method. Now if you try to load the page www.example.com/helloworld, then you will see the output

You didt it!

This means when you use your frontname only in the url, then Magento assumes index as the second url reference and index as the third url reference. Or in otherwords, www.example.com/helloworld will treat as www.example.com/helloworld/index/index. This way it will look for the controller app/code/Rkt/HelloWorld/Controller/Index/Index.php and thus executes execute() method.

That’s it.

Rajeev K Tomy

Leave a Reply

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

Back to top