As you probably know, a new approach to command line has been introduced in Magento 2. This approach is based on the CommandsList you find in Symfony, but extended with Magento2 direct injection principles.
By default you find a quite big amount of Magento tasks you can run from CLI by just typing “php bin/magento” in your SSH consolle:
Just to have an example, if you need to flush your cache from CLI you just have to type:
php bin/magento cache:flush
Sometimes you may need to add your own commands to run specific tasks from command line and in the next example we will add a new command “my:command” for a module named “My_Module”.
We will not see how to create new modules, so this tutorial assumes your already know ho to do it.
Adding a new command is quite easy, first of all we need to register it by injecting it in the Magento\Framework\Console\CommandList object using di.xml file:
<?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="my_command" xsi:type="object">My\Module\Command\Mycommand</item> </argument> </arguments> </type> ... </config>
Now Magento2 is expecting a new class Mycommand in My\Module\Command namespace.
This class myust extend Symfony\Component\Console\Command\Command:
<?php namespace My\Module\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; class ImportPage extends Command { protected function configure() { $this->setName('my:module'); $this->setDescription('My awesome command'); parent::configure(); } protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Hello world!'); } }
You are done, you just created your new command line task!
To run it from CLI just type:
php bin/magento my:command
If you need you can also add input parameters by using the input arguments interface:
In your configure method:
... protected function configure() { $this->setName('my:module'); $this->setDescription('My awesome command'); // Next line will add a new required parameter to our script $this->addArgument('number', InputArgument::REQUIRED, __('Type a number')); parent::configure(); } ... protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln("I will double your number:"); $output->writeln($input->getArgument('number')*2); } ...
Now, if we just run php bin/magento my:command we will get a “Not enough arguments” error because the number parameter is not set.
If we add the required parameter and we run run:
php bin/magento my:command 2
We should get the following output:
I will double your number: 4