Magento 2 Module Development – Step By Step Guide for 2024

Magento 2 Module Development – Step By Step Guide for 2023

What is a Magento Extension?

An extension is a logical group – that is, a directory containing blocks, controllers, helpers, and models – that is related to a specific business feature. In keeping with Magento’s commitment to optimal modularity, a module encapsulates one feature and has minimal dependencies on other modules.

Extensions and themes are the units of customization in Magento. Modules provide business features, with supporting logic, while themes strongly influence user experience and storefront appearance.

Both components have a life cycle that allows them to be installed, deleted, and disabled. From the perspective of both merchants and extension developers, modules are the central unit of the Magento organization.

The Magento Framework provides a set of core logic: PHP code, libraries, and the basic functions that are inherited by the modules and other components.

You must follow a PSR-compliant structure when building a module.

In this guide, we will help you create a simple Magento 2 extension that can be useful as a base to create more advanced extensions for your Magento 2 webshop.

Follow the Below Steps for Magento 2 Extension Development:

Disable Cache

Make sure that the Magento cache is disabled so that you don’t have to clear the cache while making changes to the extension. This will save you a lot of time in development.

You can disable the cache from Admin -> System -> Cache Management -> select all types and disable.

Developer Mode

Ensure that your Magento store is in developer mode so that all changes are reflected in real-time and you can view any errors you come across while doing the coding.

For this, you have to run commands from the terminal using SSH access. Log in to your Magento store SSH account then in the Magento root directory run the below command:

php bin/magento deploy:mode:set developer

Module Initialization

You may already have experience with this if you are Magento 1 developer and have used its terminology before for code pools. Magento 2 framework is the same but doesn’t have extra code pools. They are grouped with namespaces and have to reside in the app/code directory.

We have to first create files and directories to initialize and register the extension. Create the below directories:

app/code/Icecube
app/code/Icecube/Firstextension

After that create a file named module.xml in the directory app/code/Icecube/Firstextension/etc and place the following code:

<?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="Icecube_Firstextension" setup_version="1.0.0">
     </module>
</config>

Next, we need to register your module by creating file registration.php in the directory. app/code/Icecube/Firstextension with and inserting code:

 <!--?php 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Icecube_Firstextension',
    __DIR__
);

Create Controller

Now it’s time to define a router to use the path for all requests. Create a file named routes.xml in the directory app/code/Icecube/Firstextension/etc/frontend and place the following code:

 <?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="firstextension" frontName="firstextension">
            <module name="Icecube_Firstextension"/>
        </route>
    </router>
 </config>

By using a route with id “firstextension” we have now defined the path for the new frontend router.

We will use the frontName attribute as the first part of the URL.

Magento 2 has the URLs constructed as below:

<frontName>/<controler_folder_name>/<controller_class_name>

Our extension’s final URL becomes:

/firstextension/index/index

After the route has been defined we need to create the landing controller file index.php in the directory app/code/Icecube/Firstextension/Controller/Index with the following code:

<?php
namespace Icecube\Firstextension\Controller\Index;
use Magento\Framework\App\Action\Context;
class Index extends \Magento\Framework\App\Action\Action
{
    protected $_resultPageFactory;
 
    public function __construct(Context $context, \Magento\Framework\View\Result\PageFactory $resultPageFactory)
    {
        $this->_resultPageFactory = $resultPageFactory;
        parent::__construct($context);
    }
 
    public function execute()
    {
        $resultPage = $this->_resultPageFactory->create();
        return $resultPage;
    }
}

Each controller of Magento 1 can have defined multiple actions, while Magento 2 actions have their own classes implementing the “execute()” method.

Create Block

The next step is to a block class as a method to return the values to show on the front. In our case, a simple text to return “This is your first extension”. Create file Firstextension.php in the directory. app/code/Icecube/Firstextension/Block and put below code:

<?php
namespace Icecube\Firstextension\Block;
class Firstextension extends \Magento\Framework\View\Element\Template
{
    public function getFirstExtensionTxt()
    {
        return 'This is your first extension!';
    }
}

Create Layout and Theme

After these steps, it just needs a layout file to show the value which is returned from the extension block file. This is almost the same as Magento 1. In Magento 2 that layout files and templates reside in the view directory in your module and inside the view directory, we can have these three subdirectories: adminhtml, base, and frontend.

Here adminhtml directory is used for admin purposes, the frontend directory is used for frontend purposes, and the base directory is used for both admin and frontend files.

Let’s create a file named firstextension_index_index.xmlin directory app/code/Icecube/Firstextension/view/frontend/layout and place following code:

    
 <page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd" layout="1column">
    <body>
        <referenceContainer name="content">
            <block class="Icecube\Firstextension\Block\Firstextension" name="firstextension" template="firstextension.phtml" />
        </referenceContainer>
   </body>
 
</page>

We need to create a layout handle for each page as each controller action has a layout handle and in our case the layout handle is firstextension_index_index.

Now we have to create a phtml file to set the template of our block which we have added in the layout handle. Create firstextension.phtml in directory app/code/Icecube/Firstextension/view/frontend/templates and place following code:

 
<h1><?php echo $this->getFirstExtensionTxt(); ?> </h1>

By using $this object variable, we have referenced the block class we have created and from it, we have called the method we have defined getFirstExtensionTxt() which returns the text ‘This is your first extension!’

Deploy

Last but not the least, we have to run one command to deploy the files we have created for the extension so that it’s usable on the Magento store. Log in to your Magento store SSH account and go to the Magento root directory and run the below command:

php bin/magento setup:upgrade

You can make sure that your extension is installed properly by going to Admin → Stores → Configuration → Advanced → Advanced and checking that the module is present in the list otherwise you have to open app/etc/config.php and check the array for the ‘Icecube_Firstextension’ key, whose value should be set to 1.

And that’s all folks. Go to your browser and open the URL http://magentostore.com/firstextension/index/index and you should get the text displayed on your store page.

If you face any other technical issues while building your Magento 2 extension, Please feel free to contact us and our Magento 2 developers would be glad to assist.

Parth Patel, a skilled E-commerce Consultant and co-founder of Icecube Digital, dedicates his time to producing straightforward yet invaluable content. With a sharp attention to detail and a passion for innovation, Parth focuses on Magento, WordPress, Shopify, and other platforms in his commitment to advancing e-commerce solutions.

Leave a Reply