Console

Console commands are listed and executed by bin/magento command line tool.

  • action_name: Console action name. Example: Backup, Import
  • short_description: Console action description. Example: Backups the Magento environment, Starts product import

Snippet generation

When you generate a module with an action_name (backup) and the module is named (MageGen/Module). The generated command used by bin/magento is:

bin/magento mage2gen_module:backup

Use the snippet in the Magento 2 module creator.

Files

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="Test" xsi:type="object">Mage2Gen\Module\Console\Command\Test</item>
			</argument>
		</arguments>
	</type>
</config>

Console/Command/Test.php

<?php
declare(strict_types=1);

namespace Mage2Gen\Module\Console\Command;

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

class Test extends Command
{

    const NAME_ARGUMENT = "name";
    const NAME_OPTION = "option";

    /**
     * {@inheritdoc}
     */
    protected function execute(
        InputInterface $input,
        OutputInterface $output
    ) {
        $name = $input->getArgument(self::NAME_ARGUMENT);
        $option = $input->getOption(self::NAME_OPTION);
        $output->writeln("Hello " . $name);
    }

    /**
     * {@inheritdoc}
     */
    protected function configure()
    {
        $this->setName("mage2gen_module:test");
        $this->setDescription("Test");
        $this->setDefinition([
            new InputArgument(self::NAME_ARGUMENT, InputArgument::OPTIONAL, "Name"),
            new InputOption(self::NAME_OPTION, "-a", InputOption::VALUE_NONE, "Option functionality")
        ]);
        parent::configure();
    }
}