Cookies setting

Cookies help us enhance your experience on our site by storing information about your preferences and interactions. You can customize your cookie settings by choosing which cookies to allow. Please note that disabling certain cookies might impact the functionality and features of our services, such as personalized content and suggestions. Cookie Policy

Cookie Policy
Essential cookies

These cookies are strictly necessary for the site to work and may not be disabled.

Information
Always enabled
Advertising cookies

Advertising cookies deliver ads relevant to your interests, limit ad frequency, and measure ad effectiveness.

Information
Analytics cookies

Analytics cookies collect information and report website usage statistics without personally identifying individual visitors to Google.

Information
mageplaza.com

How to Add Command Line Into Console CLI in Magento 2?

Vinh Jacker | 12-18-2024

How to Add Command Line Into Console CLI in Magento 2?

Many Magento 2 store owners are tired of doing repetitive tasks like running a custom cron job or clearing cached directories. However, they still have to do these tasks because they’re still essential to the M2 system. Thankfully, there is an effective solution to this issue. You can simplify these routine processes into a single command by following the method below to create a console command in Magento 2. Custom console commands in Magento 2 are incredibly useful for automating repetitive tasks that need to be performed the same way each time.

Step-By-Step Guide to Add New Console Command in Magento 2

In Magento 1, there was no built-in Command Line Interface (CLI). However, Magento 2 had a great update, introducing a powerful CLI. It allows you to manage actions, indexes, modules, and more.

You can even create your own custom console CLI commands to streamline specific tasks. To add a new command in the Magento 2 CLI, we first need to complete these preparation tasks below:

Once you’ve completed the initial setup, you’re ready to start creating a new CLI command in Magento 2. Before diving in, it’s important to take a moment to understand the naming conventions used in the Magento 2 CLI to ensure consistency and proper functionality.

We will use an example module Mageplaza_HelloWorld to demo for this lesson. To add an option to Magento 2 CLI, we will follow by some steps:

Step 1: Define command in di.xml

In di.xml file, you can use a type with name Magento\Framework\Console\CommandList to define the command option.

File: app/code/Mageplaza/HelloWorld/etc/di.xml

<?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="exampleSayHello" xsi:type="object">Mageplaza\HelloWorld\Console\Sayhello</item>
           </argument>
       </arguments>
   </type>
</config>

This config will declare a command class Sayhello. This class will define the command name and execute() method for this command.

Step 2: Create command class

As define in di.xml, we will create a command class:

File: app/code/Mageplaza/HelloWorld/Console/Sayhello.php

<?php
namespace Mageplaza\HelloWorld\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class Sayhello extends Command
{
   protected function configure()
   {
       $this->setName('example:sayhello');
       $this->setDescription('Demo command line');
       
       parent::configure();
   }
   protected function execute(InputInterface $input, OutputInterface $output)
   {
       $output->writeln("Hello World");
   }
}

In this function, we will define 2 methods:

  • configure() method is used to set the name, description, command line arguments of the magento 2 add command line
  • execute() method will run when we call this command line via console.

After declare this class, please flush Magento cache and type this command:

php magento --list

You will see the list of all commands. Our command will be show here

magento 2 add command line

Now you can run bin/magento example:sayhello from the command to see the result

magento 2 add command line

Now, we will add the arguments for the command.

Content would be:

<?php

namespace Mageplaza\HelloWorld\Console;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

class Sayhello extends Command
{

	const NAME = 'name';

	protected function configure()
	{

		$options = [
			new InputOption(
				self::NAME,
				null,
				InputOption::VALUE_REQUIRED,
				'Name'
			)
		];

		$this->setName('example:sayhello')
			->setDescription('Demo command line')
			->setDefinition($options);

		parent::configure();
	}

	protected function execute(InputInterface $input, OutputInterface $output)
	{
		if ($name = $input->getOption(self::NAME)) {

			$output->writeln("Hello " . $name);


		} else {

			$output->writeln("Hello World");

		}

		return $this;

	}
}

We defined name argument for command line in configure() function and get it in execute() function. Please clear cache and run php bin/magento example:sayhello --name="Join" from the command line to check the result. It will show “Hello Join”

Conclusion

And that’s how to create and add a command line into console CLI in Magento 2. With this method, businesses can save a lot of time doing repetitive tasks and focus more on strategic plans.

x
    Jacker

    With over a decade of experience crafting innovative tech solutions for ecommerce businesses built on Magento, Jacker is the mastermind behind our secure and well-functioned extensions. With his expertise in building user-friendly interfaces and robust back-end systems, Mageplaza was able to deliver exceptional Magento solutions and services for over 122K+ customers around the world.



    Related Post

    Website Support
    & Maintenance Services

    Make sure your store is not only in good shape but also thriving with a professional team yet at an affordable price.

    Get Started
    mageplaza services