Introduction to Console Commands
Magento 2 has a powerful command line framework integrated with it for performing the utility tasks such as cache cleaning, index management, module enable/disable, deployment etc. Magento Core Provides many useful commands out of the box, we can also create our own Console command for our needs.
Example Use Case: Listing themes
In this article i'll explain the Necessary steps to create our own custom console command. So in the First Part of the Article we will create a custom console command that will list the THEMES currently deployed/installed in magento2 site. In the Next article we will create a custom command to switch the frontend theme without logging in to the admin panel.
For this example, i'll skip the basic module creation step and proceed directly to the concept.
How the Command List Works
In Magento 2 the class that is responsible for creating new console command is Magento\Framework\Console\CommandList
[crayon-5bae2dbc73571739073490/]
Every Magento2 core module will instantiate the above class and register the commands.
So in order to register our own custom command we need to extend this class using di.xml.
Creating di.xml to register custom command
[crayon-5bae2dbc73581902220630/]
The type node accepts the name of the class to be extended.
So for our use case this will be "Magento\Framework\Console\CommandList" class.
Inside the arguments node we can define our commands as argument. Each item defined
under the argument node will be passed to the constructor of the base class. Under the argument we can
define the list of items, so here the command identifier and the sub class are defined.
Creating the Custom class that defines the Custom Command
The Subclass Mydons\ThemeConsoleCmd\Command\ListThemes contains two methods configure and execute
Under the configure method the command name,description and input option are defined.
Here I have added an option to skip the "Admin Theme" from the listing.
[crayon-5bae2dbc7358d461607473/]
Execute method will fetch the list of themes available in the magento2 database. It will also detect any new theme uploaded.
[crayon-5bae2dbc7359d224547694/]
Complete Code that handles the command exeuction
[crayon-5bae2dbc735a8298527786/]
Once the module is installed and enabled, we can see the custom command in the command list
Listing Commands
[crayon-5bae2dbc735b4419740196/]
Command Help
[crayon-5bae2dbc735c3964013985/]
Command in action
[crayon-5bae2dbc735cd487007519/]
The post Magento 2 create custom console command with sample usecase appeared first on Mydons.