In this tutorial I will give an overview of the console commands in Magento 2 and we will learn how to build a custom console command in Magento 2.
Magento 2 CLI
Magento has one command-line interface that performs both installation and configuration tasks. To see the full list of commands in your Magento 2 installation use the console command in your root directory:
php bin/magento list
Custom Console command
We will create a very simple command that will have a parameter as input. This will not have any eCommerce logic into it. The end goal is to have a skeleton on which you can work on. For this tutorial we will create a command that will be executed using the command:
php bin/magento mesteru:hello [name]
for example executing:
php bin/magento mesteru:hello Paul
will return “Hello Paul!”.
Lets start by creating a class called Hello in your module path VendorName\ModuleName\Console\Command
Magento 2 is using Symfony components for it’s commands so we will need to include the Symfony related classes.
You can inject using DI your own classes into the constructor, that is why for the purpose of this tutorial I included the constructor also.
The configure() method is where we set the name for the command and adding the arguments.
The execute() method is where we put all the logic to be executed by the CLI command.
Bellow is the full class implementation:
<?php namespace Mesteru\SampleModule\Console\Command; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Magento\Framework\Console\Cli; class Hello extends Command { const INPUT_KEY_NAME = 'name'; public function __construct() { //here you can inject and init your needed classes parent::__construct(); } protected function configure() { $this->setName('mesteru:hello') ->addArgument( self::INPUT_KEY_NAME, InputArgument::REQUIRED, 'Name to say hello' ); parent::configure(); } protected function execute(InputInterface $input, OutputInterface $output) { $name = $input->getArgument(self::INPUT_KEY_NAME) echo "Hello ".$name."!"; return Cli::RETURN_SUCCESS; } }
We will need also to add this to the commands list by using the di.xml configuration. So in your module VendorName\ModuleName\etc\di.xml have the following:
<?xml version="1.0"?> <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd"> <type name="Magento\Framework\Console\CommandList"> <arguments> <argument name="commands" xsi:type="array"> <item name="mesteruSayHello" xsi:type="object">Mesteru\SampleModule\Console\Command\Hello</item> </argument> </arguments> </type> </config>
This was a short overview of console commands in Magento 2. You can use this skeleton for your own logic.
You can check my previous posts about Magento 2.