In this post, we will see how we can create a new controller in Magento 2. Here are the steps:

  1. Create a new module if you don’t have one. Click here to check the steps.
  2. Create a new folder named frontend under etc folder.
  3. Create the file routes.xml inside frontend folder with following code:
    <?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="hayo" frontName="hayo">
                <module name="Mymodule_Test" />
            </route>
        </router>
    </config>

    Here hayo is the front name for the controller.

  4. Create a new folder named Controller under Test folder.
  5. Create a new folder named Basic under Test folder. This folder represents the Action Path for the controller URL.
    In Magento 2, each controller class have only one action method named execute whereas in Magento 1, we can have multiple actions in same controller.
  6. The directory structure is:
    <Mymodule>
         <Test>
              <Controller>
                 <Basic>
              <etc>
                 <frontend>
                      routes.xml
              module.xml
         registration.php
    
  7. Create a new file Index.php inside the Basic folder with following code:
    <?php
    namespace Mymodule\Test\Controller\Basic;
    
    use \Magento\Framework\App\Action\Action;
    
    class Index extends Action
    {
        public function execute()
        {
            echo "Hello from first controller";
        }
    }
    ?>
  8. Our controller is ready at this moment. The URL to call controller is like this:
    http://yoursite/front-name/action-path/controller-class

    Refresh the cache (remove cache, generation folder under var) and execute the following URL to test the controller:

    http://yoursite/hayo/basic/index