Create Magento 2 Module


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.

    1. Create name space under app/code. Eg: app/code/Magleaks
    2. Create your module under your name space. Eg: app/code/Magleaks/Tutorial1
    3. 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.)
    4. Copy module deceleration from core module like Magento_Catalog and change module name, and remove other contents.
    5. <?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>
      
    6. Run setup upgrade to configure the module. (<Magento 2 root>/bin/magento setup:upgrade)
    7. New module name should be in module list. Also you can verify this in admin. (Stores=>Configuration=>Advanced=>Advanced)
    8. Now lets create controller. Create controller class Magleaks/Tutorial1/Controller/Tutorial1/Index.php as follows.
    9. <?php
      namespace Magleaks\Tutorial1\Controller\Tutorial1;
      
      class Index extends \Magento\Framework\App\Action\Action {
          
          public function execute() {
              echo 'We are here !'; 
          }
          
      }
      

       

    10. Create file Magleaks\Turorial1\etc\frontend\routes.xml for route. You can copy content from Magento core and edit.
    11. 
      <?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>
      
    12. Now clear config cache and access controller via front end. /tutorial1/tutorial1/index

Check following video.
How to create M2 module

Gihan Kavinga

Technical lead at Netstarter PTY Ltd. Magento certified developer plus. Oracle certified professional Business Component Developer. Linux system admin.

Leave a Reply

  • (will not be published)