Create a Magento Controller

Product

Want to learn everything about M2?

Quickly learn and reference all Magento programming basics, concepts & patterns, even with no prior experience.

How to Create a Magento Controller

The next part of the URL is the controllerName. This name corresponds to a class within the Controller folder of your module. Let’s create a new directory within our module named Controller:

app/code/Macademy/Jumpstart/Controller/

Within this directory, we’ll create another directory named after our controllerName. Magento uses index by default if that part of the URL is not present. So, let’s create a folder named Index. Note how we are capitalizing the I in Index — this is important:

app/code/Macademy/Jumpstart/Controller/Index

Create a Controller Action

Our next part of the URL is the actionName. This refers to the specific class that will be responsible for handling this request, and will live within our controllerName folder. Again, if this part of the URL is not present, Magento defaults it back to index. Let’s create a new file for this class and name it Index.php.

<?php

declare(strict_types=1);

namespace Macademy\\Jumpstart\\Controller\\Index;

use Magento\\Framework\\App\\Action\\HttpGetActionInterface;

class Index implements HttpGetActionInterface
{
    public function execute()
    {
        die('jumpstart!');
    }
}

Our controller actions should implement the HttpGetActionInterface. Implementing interfaces ensures our code includes all the functions defined in the interface, which aids in building reliable, dependable code.

For now, we will just use the die() function to output some text to make sure things are working.

If we now visit https://magento.test/jumpstart, we’ll see our text displayed on the screen! If a 404 error page still displays, try clearing the Magento cache with bin/magento cache:clean to ensure that your module's latest XML files are registered.

Complete and Continue  
Extra lesson content locked
Enroll to access all lessons, source code & comments.
Enroll now to Unlock