Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 42 ยท Requests and Output

Routing and Controllers

Learn how Magento maps a URL to a controller action: routes.xml, frontName, the Controller folder layout, HTTP method interfaces and result factories.

When a browser asks for /hello/greeting/show, something has to decide which PHP class answers. In Magento that decision is made by routers. The standard router reads a small XML declaration from your module, turns the URL into a class name, and calls that class. The class is a controller action: one class, one execute() method, one job.

Magento cannot run on this site, so the real XML and PHP in this lesson are read-only. Below them you will find a runnable stand-in router that follows the same rules, so you can try URLs and see which class would answer.

Declaring a route in routes.xml

A module that wants to serve storefront pages adds etc/frontend/routes.xml:

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 id="acme_hello" frontName="hello">
            <module name="Acme_Hello"/>
        </route>
    </router>
</config>

There are three names to keep apart:

  • router id="standard" says which router handles the route. Storefront modules use standard. The admin has its own router, covered in Admin Controllers, Menus and ACL.
  • route id is an internal, unique identifier. It also becomes the first part of the layout handle for pages (see Layout XML and Handles).
  • frontName is what appears in the URL, the first path segment after the domain. It is usually short and readable.

The module node tells the router which module's Controller folder to search. The file lives in etc/frontend/ because routes belong to an area, as explained in Areas and Configuration Files.

From URL to class name

The standard router splits the path into three parts and then looks for a class in a fixed place:

Text
/hello/greeting/show
  |      |        |
  |      |        +-- action  -> class Show
  |      +----------- folder  -> Controller/Greeting
  +------------------ frontName -> module Acme_Hello

That URL is handled by Acme\Hello\Controller\Greeting\Show, which is the file Controller/Greeting/Show.php in the module. If you leave out parts, they default to index:

URL Class
/hello Acme\Hello\Controller\Index\Index
/hello/greeting Acme\Hello\Controller\Greeting\Index
/hello/greeting/show Acme\Hello\Controller\Greeting\Show

The folder and action names in the URL are lowercase; the router capitalizes them to find the class. Anything after the action is treated as parameters. Magento's classic form is key and value pairs in the path, such as /hello/greeting/show/id/42, which makes id equal to 42. Ordinary query strings (?id=42) work too. Both are explained in Request, Response and Result Types.

flowchart LR
    A["GET /hello/greeting/show/id/42"] --> B["Standard router"]
    B --> C["frontName 'hello'<br/>finds Acme_Hello"]
    C --> D["Controller class Show<br/>in folder Greeting"]
    D --> E["execute() returns a result"]
    E --> F["Response sent to browser"]

The router resolves the frontName to a module, builds the class name from the next two segments and calls its execute() method.

Writing a controller action

Modern controller actions are small classes that implement an interface naming the HTTP method they accept:

PHP
<?php

namespace Acme\Hello\Controller\Greeting;

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

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

    public function execute(): ResultInterface
    {
        return $this->resultFactory->create(ResultFactory::TYPE_PAGE);
    }
}

Points worth noticing:

  • HttpGetActionInterface is a marker interface: it declares that this action answers GET requests. Its sibling HttpPostActionInterface is for POST. If a request arrives with a method the action does not declare, Magento refuses it. Declaring the method is good practice for security and for clear intent.
  • Dependencies come through the constructor. Nothing here calls the object manager directly. See The Object Manager and Constructor Injection.
  • execute() returns a result object, not text. The framework turns that object into the HTTP response. This keeps controllers easy to test and lets Magento apply caching and headers consistently.

Older code, and many third-party modules, extend Magento\Framework\App\Action\Action and get the request and context from the parent. That still works, but new code should prefer the small interface style above.

Result factories

An action usually needs one of a handful of results. You can ask ResultFactory for them by constant, or inject a dedicated factory such as PageFactory or JsonFactory:

Constant Result Typical use
TYPE_PAGE A full page built from layout XML Storefront pages
TYPE_JSON JSON body AJAX endpoints
TYPE_RAW Raw text or markup Simple outputs, feeds
TYPE_REDIRECT HTTP redirect After a form post
TYPE_FORWARD Internal hand-off to another action Reuse without a new request

The details of each belong to the next lesson. The key idea here is that the controller asks for a result and returns it.

Building URLs

Never hand-write URLs in PHP or templates. Inject Magento\Framework\UrlInterface and ask it:

PHP
$url = $this->urlBuilder->getUrl('hello/greeting/show', ['id' => 42]);

The string is frontName/folder/action, called a route path. The builder adds the store's base URL, applies the store code if your setup uses it, and appends the parameters. Using it means your links keep working when someone changes the base URL or enables a language prefix.

Try it: a mini standard router

This stand-in reads a route table like the one from routes.xml, splits a path the way the standard router does, applies the index defaults, parses path parameters and falls back to a 404 action. It does not check that the class really exists on disk, and it does not support the other routers (CMS, default); real Magento is far richer. The goal is to make the mapping rules concrete.

PHP Mapping paths to controller classes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice how /hello and /hello/greeting need no extra configuration: the missing segments become index. The unknown front name goes to a no-route page, which is also what a real store shows for a URL nobody claims.

The next stand-in dispatches to action objects and enforces the HTTP-method interfaces, the way a real action declares what it accepts.

PHP Actions that declare their HTTP method

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

In real Magento the framework performs this method check for you when an action implements one of the interfaces; this stand-in only mirrors the idea. If you want a refresher on interfaces in PHP, see Abstract Classes and Interfaces.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which class handles the URL /hello/greeting/show for a route with frontName "hello" in module Acme_Hello?

    The first segment selects the module, the second is the Controller subfolder and the third is the action class.
  2. 2. What is the difference between a route id and a frontName?

    The frontName is what visitors see in the URL. The route id is internal and also starts the layout handle name.
  3. 3. What does an action's execute() method return in modern Magento?

    Actions return a ResultInterface. The framework renders it into the response, which keeps actions testable.
  4. 4. Why should you build URLs with UrlInterface::getUrl() instead of writing them by hand?

    The URL builder adds the right base URL and store details, so hard-coded paths do not break when the setup changes.

Summary

  • etc/frontend/routes.xml declares a route: a router (usually standard), a unique route id, a frontName and the owning module.
  • A URL /frontName/folder/action maps to Vendor\Module\Controller\Folder\Action; missing parts default to index.
  • Parameters can follow the action as /key/value pairs or arrive in the query string.
  • Actions implement HttpGetActionInterface or HttpPostActionInterface and return a result from execute().
  • Use result factories for pages, JSON, raw output, redirects and forwards, and UrlInterface to build links.

Next, look closer at the objects going in and out in Request, Response and Result Types.