This topic gives you the idea that how magento specialist can create a custom Module for Magento2. Follow the 6 steps
- Create the module directory for the module
- Define the module by module.xml
- Register the module by registration.php
- Install setup and enable the module
- Route creation for the module
- Create controller and url action
Create the module directory for the module :
We are using module vendor Toweringmedia and module name is Mymodule. So we need to create a new directory in :
app/code/Toweringmedia /Mymodule
Define the module by module.xml
We need declare the module definition in module etc directory. Magento 2 will use it to recognize the module’s name and module’s version from module.xml file. Create the file in this directory
app/code/Toweringmedia /Mymodule/etc/module.xml
And paste the following code in the file.
<?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=”Toweringmedia _Mymodule” setup_version=”1.0.0″ />
</config>
* 1.0.0 is the module version
Register the module by registration.php
Create the file registration.php in into the directory
app/code/Toweringmedia /Mymodule/registration.php
and add the following code there.
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
‘Toweringmedia _Mymodule‘,
__DIR__
);
Install setup and enable the module
After we can install the module through cli command. Now open your terminal and run these command from magento root directory:
php bin/magento setup:upgrade
Route creation for the module
we need to init router name for the module before creating any controllers and actions.
Create the routers.xml file
app/code/Toweringmedia /Mymodule/etc/frontend/routes.xml
and add the following code there.
<?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=”toweringmedia” frontName=”mymodule”>
<module name=”Toweringmedia_Mymodule” />
</route>
</router>
</config>
Create controller and url action
In the final step, we need to create a url for displaying in browser: “My Module”.
Create the action file:
app/code/Toweringmedia/Mymodule/Controller/Index/Index.php
Add the following code
<?php
namespace Toweringmedia\Mymodule/Controller\Index;
class Index extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context)
{
return parent::__construct($context);
}
public function execute()
{
echo ‘My Module’;
exit;
}
}
Now open the link http://<magento_url>/mymodule/index/index you will the result “My Module“.