You already have the list of Magento 2 SSH commands.
Command Line Interface (CLI) allows the developers to use default commands to manage modules and indexes, generate classes and carry out database updates. The good news is, Magento developers can add their own custom CLI commands. Today, I have come up with a solution to add custom CLI command in Magento 2.
Magento 2 CLI commands are useful for tasks like:
- Install Magento
- Update database schema
- Cache clear
- Managing indexes, including reindexing
- Creating translation dictionaries and translation packages.
- Generating non-existent classes such as factories and interceptors for plug-ins, generating the dependency injection configuration for the object manager.
- Deploying static view files.
- Creating CSS from Less.
Here, I have taken an example to add CLI commands in Magento 2 that can perform multiple tasks like caching, indexing, deploying and upgrading. And after you add CLI commands you can also set system configuration value using CLI command after that you can set Magento 2 default configuration option value as well as third-party extension configuration value from the CLI command.
You can use this solution to perform any task with a custom command instead of from the backend which would only be quicker!
Method to Add CLI Commands in Magento 2
Step 1: Create di.xml at path [Vendor]\[Module]\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="mycustomcommand" xsi:type="object">[Vendor]\[Module]\Console\CustomCommand</item> </argument> </arguments> </type> </config>
Step 2: Create CustomCommand.php at path [Vendor]\[Module]\Console\CustomCommand.php
<?php namespace [Vendor]\[Module]\Console; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; /** * Class SomeCommand */ class CustomCommand extends Command { /** * @inheritDoc */ protected function configure() { $this->setName('my:custom:command'); $this->setDescription('This is my first console command.'); parent::configure(); } /** * @param InputInterface $input * @param OutputInterface $output * * @return null|int */ protected function execute(InputInterface $input, OutputInterface $output) { /* your code here */ $output->writeln("Custom command Run Successfully"); } }
Clear cache after the above implementation.
View this command using php bin/magento list in console
To run your command:php bin/magento my:custom:command
That was it!
Feel free to share the solution with fellow developers via social media.
Thanks.