Magento 2 Create a new simple module

In this blog post, we will see how to create a simple module with router displaying “Welcome to Magento 2”.

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="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magetec_Welcome" setup_version="0.0.1"/>
</config>

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

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


<?php
MagentoFrameworkComponentComponentRegistrar::register(
 MagentoFrameworkComponentComponentRegistrar::MODULE,
 'Magetec_Welcome',
 __DIR__
);

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
OR
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="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/App/etc/routes.xsd">
    <router id="standard">
        <route id="welcome" frontName="welcome">
            <module name="Magetec_Welcome" />
        </route>
    </router>
</config>

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

<?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';
        exit;
    }
}

Default redirect: baseurl/index.php/welcome/index/index
That’s it! you have created your custom module with custom router action.

Leave a Reply