Controllers in Magento 2 - Tutorial - Paul Meștereagă
Magento 2

Controllers in Magento 2

Learn about the Controller Layer in Magento 2. Check the step by step tutorial on how to create Frontend and Backend controllers in Magento 2.

author

Paul Mestereaga

February 5, 2018

Let’s continue our series with a tutorial about Controllers in Magento 2. You can check my previous posts about Magento 2.

Routing

In Magento 2 we have two routing configurations. One for frontend area and one for backend area. Lets create etc/frontend/routes.xml.
In this file we declare our frontend router in the node <router></router> with it’s route and frontend name. You can see the source code below.

<!--?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 id="mesteru" frontname="mesteru">
            <module name="Mesteru_FirstModule">
        </module></route>
    </router>
</config>

The second file is etc/adminhtml/routes.xml where we declare the backend router in the same way, except that the router id is admin.

<!--?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="admin">
        <route id="mesteru" frontname="mesteru">
            <module name="Mesteru_FirstModule">
        </module></route>
    </router>
</config>

Frontend Controllers

Lets create the folder Controller in the root folder of our module. In Magento 2 controllers are not classes but folders. So for the Index controller we create the Index folder inside Controller. Here we define the action classes. For example Index.php where we define the class for Index action.

In this example we also use the ResultFactory class. The execute() method should return resultInterface or responseInterface.
Here is an example that shows a ‘Hello World’ message on a blank page:

<?php
namespace Mesteru\FirstModule\Controller\Index;
 
use Magento\Framework\Controller\ResultFactory;
 
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $result =  $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $result->setContents('Hello World');
        return $result;
    }
}
?>

Backend Controllers

For the backend controllers we create the Adminhtml under Controller namespace. Here we create the Index controller folder and the action file Index.php Here is the example of a backend controller:

<?php
namespace Mesteru\FirsModule\Controller\Adminhtml\Index;
 
use Magento\Framework\Controller\ResultFactory;
 
class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $result->setContents('Hello World');
        return $result;
    }
}
?>

Check the routes

First let’s flush the caches:

php bin/magento cache:flush

Go into the browser and navigate to yourmagento.com/mesteru to access the frontend controller.

To access the backend controller, log into the admin area. You will notice the secret key in the url and for now let’s disable it, just for development purposes. Go to:

Stores \ Configuration \ Advanced \ Admin \ Aecurity \ Add secret key to url -> No

Now we can test our controller yourmagento.com/admin/mesteru

Conclusion

Now you know how to create Controllers in Magento 2. If you have any question don’t hesitate to leave a message in the comments section bellow.
In my next post I will talk about the View layer and how to use the controller to retun the views.

Get the Code

You can get the complete code on my github profile here.

Magento 2 from Zero to Beginner Free Online Course

In 10 hours you will have all the basic knowledge so that you could develop your modules without wandering around how to implement stuff.

Related Posts

Magento checkout optimization

15 Dec 2022

|

Paul Mestereaga

Optimizing the checkout process on your Magento eCommerce website is essential for increasing conversions and improving customer satisfaction. A seamless checkout experience can make all the difference in the success of your online store.

3 Things That Kill Your Magento Store’s Conversion Rate

10 Dec 2021

|

Paul Mestereaga

The store receives a lot of traffic, and you market to the right audience. The brand is actively promoted on social media and succeeds in SEO, so the marketing efforts appear to be working.
But what if it doesn’t lead to many sales?

optimize-magento-preview

FREE!

Magento 2
Optimization guide

Wondered how you can make your Magento load faster? Wonder no more. Here is a step by step guide that helps you.