Magento 2 Create a New Simple Module


In this blog post of Magento 2, we will see how to create a simple module with router. It will display the output as “Welcome to Magento 2” text on browser.

Steps to create our custom module in Magento 2:

1) We need to create a Namespace_ModuleName or VendorName_ModuleName like Magetec_Welcome.

Location: app/code/Magetec/Welcome

Note: Codepools(core/community/local) in magento 1 are completely removed in magento 2.

2) Next we need to create a registration xml file of our module

Location: app/code/Magetec/Welcome/etc/module.xml

<?xml version = "1.0"?>
<config xmlns:xsi=""
    <module name="Magetec_Welcome" setup_version="0.0.1"/>

3) Now we need to register our module in magento framework directory

Location: app/code/Magetec/Welcome/Registration.php


4) Next we need to enable our module in magento environment by two alternative ways
a) Go to “app/etc/config.php” and edit file to add ‘Magetec_Welcome’ => 1
a) Go to command shell and run command “php bin/magento module:enable Magetec_Welcome” (this will enable our module)

b) Go to command shell and run command “php bin/magento setup:upgrade” (this will register / upgrade our module version in database)

5) Now we will create our module router with http://baseurl/index.php/route_id/controller/action

Location: app/code/Magetec/Welcome/etc/frontend/routes.xml

<?xml version="1.0"?>
<config xmlns:xsi="" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="welcome" frontName="welcome">
            <module name="Magetec_Welcome" />

Note: Keep route id and frontName always same to avoid any uncertain issues.

6) Create our action class file as class name will be an action name (you need to create a new file for every new action in magento 2)

Location: app/code/Magetec/Welcome/Controller/Welcome/DoWelcome.php


namespace MagetecWelcomeControllerWelcome;
 * Class DoWelcome
 * @package MagetecWelcomeControllerWelcome
class DoWelcome extends MagentoFrameworkAppActionAction
     * DoWelcome constructor.
     * @param MagentoFrameworkAppActionContext $context
    public function __construct(MagentoFrameworkAppActionContext $context)
        return parent::__construct($context);

    public function execute()
        echo 'Welcome to Magento 2';

Default redirect: baseurl/router_name/controller_name/action_name
That’s it! you have created your custom module with custom router action.

Hope this helps you Guys!

Leave a Reply