Programmatically: How to create a custom module in Magento 2
Step 1: Create a new directory
Create a new directory within the app/code directory of your Magento 2 project. For example, let's name it MyCompany_MyModule.
Step 2: Create the module declaration file
In the MyCompany_MyModule directory, create a new file called registration.php. This file will contain the module declaration:
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'MyCompany_MyModule',
__DIR__
);
This file tells Magento that this is a module and provides the module name (MyCompany_MyModule) and the directory path (__DIR__, which refers to the current directory).
Step 3: Create the module configuration file
Create a new file called module.xml in the etc directory within the MyCompany_MyModule directory:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/moduleconfig.xsd">
<module name="MyCompany_MyModule" setup_version="1.0.0">
<dependencies>
<module name="Magento_Core" />
</dependencies>
</module>
</config>
This file declares the module and specifies its dependencies (in this case, the Magento_Core module).
Step 4: Create the module's controllers, models, and blocks
You can now create your custom controllers, models, and blocks within the Controller, Model, and Block directories respectively.
For example, let's create a simple controller:
// MyCompany/MyModule/Controller/IndexController.php
namespace MyCompany\MyModule\Controller;
class IndexController extends \Magento\Framework\App\Action\Action
{
public function execute()
{
// Your code here...
return $this->getResult();
}
}
Step 5: Add routing for the controller
Create a new file called routes.xml in the etc directory:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
<routes>
<route id="my_module_index" url="'/' prefix="">
<module name="MyCompany_MyModule"/>
</route>
</routes>
</config>
This file defines a route for your controller.
Step 6: Update the composer.json file
Add the following line to your composer.json file:
"psr-4": {
"MyCompany\\MyModule\\": "app/code/MyCompany/MyModule/"
This tells Composer where to find your module's PHP files.
Step 7: Run the command to enable and deploy your module
Run the following commands in your terminal:
php bin/magento module:deploy --area frontend
php bin/magento setup:upgrade
Your custom module should now be enabled and available in your Magento 2 instance.