Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
How to Create a Simple Hello World Module with the Custom Route for Magento 2
Andriy Zhuk Avatar

To begin with, we should create a folder with an extension for making a simple Hello World module with the custom route for Magento 2. As you may also know, in Magento 2 – there are no code pools like in Magento 1.x.

That is why, we should create a vendor folder right there in the app/code folder: magentoroot/app/code/Atwix/HelloWorld.

And the configuration file should be placed inside of our module in the directory named etc. Note that in Magento 2 it is called module.xml instead of config.xml (in Magento 1.x): magentoroot/app/code/Atwix/HelloWorld/etc/module.xml.

Therefore, it contains the following code:

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Atwix_HelloWorld" schema_version="2.0.0">
    </module>
</config>

Moreover, if the module contains the dependencies, the module’s node should look like this:

<module name="Atwix_HelloWorld" schema_version="2.0.0">
        <sequence>
            <module name="Magento_Core"/>
            <module name="Magento_Store"/>
        </sequence>
    </module>

Next step is declaring a frontend router – consequently, create the routes.xml file by the following path: magentoroot/app/code/Atwix/HelloWorld/etc/frontend/routes.xml.

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

The first section of the route string indicates which node Magento should look at to find the URL’s front name.

Then, the router ID shows which router we will use: frontend or adminhtml (the same like in Magento 1.x). Pay attention that the frontName is the first part of the URL and it should be unique.

Finally, we should create our Controller action: magentoroot/app/code/Atwix/HelloWorld/Controller/Index/Index.php.

<?php
namespace Atwix\HelloWorld\Controller\Index;

class Index extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        echo 'Hello World!';
    }
}

We want to admit that there are no class names like in Magento 1.x, and we use namespaces instead. Also, we have a class for each action which implements the execute method in the place of the controller classes with multiple methods.

That’s all, we have implemented a controller action.

We hope our tips will be useful for beginning working with Magento 2. Please do not hesitate to ask us any additional questions or add your feedback.