04 – Magento learning – Day 4/30 – How to create a custom extension in Magento?

To create a custom extension in Magento 2, follow these steps:

Set up the Extension Structure: In the root directory of your Magento installation, navigate to app/code. Create a directory structure for your extension as follows:

HTML

Create the registration.php File: Inside the ModuleName directory, create a registration.php file with the following content:php

HTML


Create the module.xml File: Inside the ModuleName directory, create a etc directory. Inside the etc directory, create a module.xml file with the following content:xml

HTML

Create the etc/di.xml File: Inside the ModuleName/etc directory, create a di.xml file. This file will define the dependency injection configuration for your extension.

Create a Controller: Inside the ModuleName directory, create a Controller directory. Inside the Controller directory, create another directory called Index. Inside the Index directory, create a PHP file with the following content:

HTML

Create a routes.xml File: Inside the ModuleName/etc directory, create a frontend directory. Inside the frontend directory, create a routes.xml file with the following content:

HTML

Run Setup Upgrade: Open a command-line interface, navigate to your Magento installation root directory, and run the following command:

HTML

Verify the Extension: Open a web browser and access your Magento store. You should be able to access the URL path defined in the controller. For example, if you defined the frontName as “route” in routes.xml and the controller name as “index” in step 5, you can access the URL at /route/index/index.

Create a Block: Inside the ModuleName directory, create a Block directory. Inside the Block directory, create a PHP file with the following content:

HTML

Create a Layout XML File: Inside the ModuleName directory, create a view/frontend/layout directory. Inside the layout directory, create an XML file (e.g., custom_layout.xml) with the following content:

Create a Template File: Inside the ModuleName directory, create a view/frontend/templates directory. Inside the templates directory, create a .phtml file (e.g., custom_template.phtml) and implement the desired HTML markup and PHP logic for your custom block.

Create a Controller to Handle Form Submission: Inside the ModuleName/Controller/Index directory, create another PHP file (e.g., Save.php) to handle the form submission and perform the desired actions. Implement the necessary logic inside the execute() method.

Update routes.xml to Include the New Controller: Modify the existing routes.xml file to include the new controller by adding another route entry:

HTML

Run Setup Upgrade: Again, run the following command to apply the changes:

HTML

Clear Cache: Clear the Magento cache to ensure that your changes take effect:

HTML