Day 2: Add Custom Route & Controller in Magento 2

Welcome to Day 2 of the Magento Advent Calendar! Today we’re adding a custom route and controller in Magento 2 — one of the most essential building blocks for module development.

Yesterday we created a simple module skeleton.
Today we’ll extend that module by adding an action that responds to a custom URL.
We want to build something like:

/custom/example/index

Create Routes File

Inside our module, create etc/frontend/routes.xml file

<?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="custom" frontName="custom">
            <module name="MageMastery_Module"/>
        </route>
    </router>
</config>

id=”custom” – internal name for the route

frontName=”custom” – the first part of the URL

This connects the frontName to our module.

Create Controller Class

Next, we create an action controller Controller/Example/Index.php

<?php

declare(strict_types=1);

namespace MageMastery\Module\Controller\Example;

use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\Raw;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Controller\ResultInterface;

class Index implements HttpGetActionInterface
{
    public function __construct(private readonly ResultFactory $resultFactory)
    {}

    public function execute(): ResultInterface
    {
        /** @var Raw $result */
        $result = $this->resultFactory->create(ResultFactory::TYPE_RAW);
        $result->setContents('Hello from custom controller!');
        return $result;
    }
}

We implement HttpGetActionInterface — meaning this action responds to GET requests.

Returning a RAW response keeps the example clean and simple.

Clear the cache and navigate to the https://magento.test/custom/example/index and if everything is correct, you should see:

“Hello from custom controller!”

Today we learned how to:
✓ Register a custom route
✓ Add a controller action
✓ Output a simple response

I’ve also create a video for Day 2 of the Magento Advent Calendar

Similar Posts

Leave a Reply