Magento 2 create custom console command with sample usecase

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

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

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.

Execute method will fetch the list of themes available in the magento2 database. It will also detect any new theme uploaded.

Complete Code that handles the command exeuction

Once the module is installed and enabled, we can see the custom command in the command list

Listing Commands

Command Help

Command in action