Day 13/100: Adding a Custom Command in Magento 2 CLI 💻
Hello LinkedIn Family!
Welcome to Day 13 of my Magento 2 journey! Today, we’re diving into the command-line interface (CLI) in Magento 2 by creating a custom command. Magento's CLI provides a powerful way to execute various operations like setup, deployment, and caching, but you can also extend it with your own commands.
Step-by-Step Guide to Adding a Custom Command:
1) Create the Command Class
First, create the command class that will handle the execution logic.
Location:
Here’s the content for :
: This defines the command name, which will be used when running the command ().
: This provides a description that will appear in the help section of the Magento CLI.
: This is where the logic of the command goes. Here, we simply print a message to the console using .
2) Register the Command in di.xml
Next, we need to register the custom command in Magento’s dependency injection configuration.
Location:
Here’s the content for :
Command Registration: We add the custom command to Magento’s command list by mapping the command class in the array.
3) Module Registration and Declaration
Module Registration ():
Module Declaration ():
4) Run the Custom Command
After setting everything up, it's time to run the command!
To do so, follow these steps:
1) Deploy the Module:
Run the following command to enable and deploy the module:
2) Run the Custom Command:
To run the custom CLI command, type:
You should see the output:
How It Works:
1) Command Class ():
This class defines the command name () and contains the logic inside the method. When the command is called, the logic in is executed, printing a message.
2) Dependency Injection ():
The custom command is registered in Magento’s dependency injection system by adding it to the list of commands. Magento automatically loads it when the CLI is used.
3) Running the Command:
The command can be executed through Magento’s CLI interface like any other built-in command. This allows you to extend Magento’s functionality by adding custom operations or logic that can be triggered from the command line.
That’s it for Day 13! You’ve successfully created and run a custom CLI command in Magento 2. This opens the door to automating tasks and adding custom functionality that can be triggered directly from the command line.
Stay tuned for the next challenge as we continue exploring more advanced Magento 2 features!