Magento 2 module structure is more organized than Magento 1. It keeps all views, controllers and config files in one directory. This make it easier to maintain and develop modules. Let’s see how to create simple module with controller.
- Create name space under app/code. Eg: app/code/Magleaks
- Create your module under your name space. Eg: app/code/Magleaks/Tutorial1
- Create module.xml file under module etc folder. app/code/Magleaks/Tutorial1/etc/module.xml (this is the minimum requirement for module. No need to create module xmls under etc.)
- Copy module deceleration from core module like Magento_Catalog and change module name, and remove other contents.
- Run setup upgrade to configure the module. (<Magento 2 root>/bin/magento setup:upgrade)
- New module name should be in module list. Also you can verify this in admin. (Stores=>Configuration=>Advanced=>Advanced)
- Now lets create controller. Create controller class Magleaks/Tutorial1/Controller/Tutorial1/Index.php as follows.
- Create file Magleaks\Turorial1\etc\frontend\routes.xml for route. You can copy content from Magento core and edit.
- Now clear config cache and access controller via front end. /tutorial1/tutorial1/index
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Magleaks_Tutorial1" setup_version="2.0.0">
</module>
</config>
<?php
namespace Magleaks\Tutorial1\Controller\Tutorial1;
class Index extends \Magento\Framework\App\Action\Action {
public function execute() {
echo 'We are here !';
}
}
<?xml version="1.0" encoding="UTF-8"?>
<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="magleaks" frontName="tutorial1">
<module name="Magleaks_Tutorial1" />
</route>
</router>
</config>
Check following video.
How to create M2 module