Blank Module Structure
Creating a new composer-installed Magento 2 module¶
Files in the module¶
Folder structure¶
Repo root
├── etc
│ └── module.xml
├── composer.json
└── registration.php
etc/module.xml¶
<?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="VendorName_ModuleName" setup_version="0.0.1"/>
</config>
composer.json¶
This file is mostly autogenerated by composer init
, but you'll need to add the autoload
node yourself so Magento knows what to do with it.
{
"name": "vendorname/modulename",
"description": "A module to do things",
"authors": [
{
"name": "Your Name Here",
"email": "you@domain.co.uk"
}
],
"require": {},
"autoload": { // Needed for Magento autoloading from vendor/
"files": [
"registration.php"
],
"psr-4": {
"VendorName\\ModuleName\\": ""
}
}
}
registration.php¶
<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'VendorName_ModuleName',
__DIR__
);
Installing the Module into Magento 2¶
Adding a git repository to composer¶
Note this step isn't needed for packages on Packagist.
{
...
repositories {
...
"ec-modulename": {
"type": "git",
"url": "user@host:/path/to/git/repo"
}
...
}
...
}
Installing the module¶
composer require "vendorname/modulename": "dev-master"
The package is then installed in Magento at vendor/{vendorname}/{modulename}
Adding a new Route¶
Configuring a new route¶
{module_root}/etc/frontend/routes.xml:
<?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="routename" frontName="routename">
<module name="VendorName_ModuleName" />
</route>
</router>
</config>
Create the controller¶
{module_root}/Controller/Index/Index.php
<?php
namespace VendorName\ModuleName\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;
class Index extends Action
{
public function execute()
{
$page = $this->resultFactory->create(ResultFactory::TYPE_PAGE);
return $page;
}
}