Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Magento 2 Development Quick Start Guide

You're reading from   Magento 2 Development Quick Start Guide Build better stores by extending Magento

Arrow left icon
Product type Paperback
Published in Sep 2018
Publisher Packt
ISBN-13 9781789343441
Length 218 pages
Edition 1st Edition
Languages
Tools
Concepts
Arrow right icon
Author (1):
Arrow left icon
Branko Ajzele Branko Ajzele
Author Profile Icon Branko Ajzele
Branko Ajzele
Arrow right icon
View More author details
Toc

Table of Contents (11) Chapters Close

Preface 1. Understanding the Magento Architecture FREE CHAPTER 2. Working with Entities 3. Understanding Web APIs 4. Building and Distributing Extensions 5. Developing for Admin 6. Developing for Storefront 7. Customizing Catalog Behavior 8. Customizing Checkout Experiences 9. Customizing Customer Interactions 10. Other Books You May Enjoy

Console commands

The built-in bin/magento tool plays a major role not just in Magento development, but in production deployments as well.

Right out of the box, it provides a dozen commands that we can use to manage caches, indexers, dependency compilation, deploying static view files, creating CSS from LESS, putting our store to maintenance, installing modules, and more.

Quite easily, Magento enables us to add our own commands to its Symfony-like command-line interface (CLI). The Magento CLI essentially extends from Symfony\Component\Console\Command.

The real value in creating our own command lies in the arguments and options that we can make available, thus passing dynamic information to the command.

Magento console commands reside under the <ModuleName>/Console directory, which can further be organized to better accommodate our commands. Magento mostly uses the <ModuleName>/Console/Command directory to place the actual CLI command class, whereas various options and other accompanying classes reside in the <ModuleName>/Console directory.

Conceptually, creating a new CLI command is as easy as doing the following:

  1. Creating the command class
  2. Wiring it up via di.xml
  3. Clearing the cache and compiled directories

Let's create our own simple console command. We will start off by creating the <MAGELICIOUS_DIR>/Core/Console/Command/RunStockImportCommand.php file with the following content:

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

class RunStockImportCommand extends Command {
const ORDER_ID_ARGUMENT = 'order_id';
const DAYS_BACK_OPTION = 'days_back';

protected function configure() {
$this->setName('magelicious:stock:import')
->setDescription('The Magelicious Stock Import.')
->setDefinition([
new InputArgument(
self::ORDER_ID_ARGUMENT, /* name */
InputArgument::REQUIRED, /* mode REQUIRED or OPTIONAL */
'The argument to set.', /* description */
null /* default */
),
new InputOption(
self::DAYS_BACK_OPTION, /* name */
null, /* shortcut */
InputOption::VALUE_OPTIONAL, /* VALUE_NONE or VALUE_REQUIRED or VALUE_OPTIONAL or VALUE_IS_ARRAY */
'The option to set.' /* description */
)
]);
parent::configure();
}

protected function execute(InputInterface $input, OutputInterface $output) {
try {
$output->setDecorated(true);
// $input->getArgument(self::ORDER_ID_ARGUMENT);
// $input->getOption(self::DAYS_BACK_OPTION);
// green text
$output->writeln('<info>The info message.</info>');
// yellow text
$output->writeln('<comment>The comment message.</comment>');
// black text on a cyan background
$output->writeln('<question>The question message.</question>');
return \Magento\Framework\Console\Cli::RETURN_SUCCESS;
} catch (\Exception $e) {
// white text on a red background
$output->writeln('<error>' . $e->getMessage() . '</error>');
if ($output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) {
$output->writeln($e->getTraceAsString());
}
return \Magento\Framework\Console\Cli::RETURN_FAILURE;
}
}
}

We then wire it up via <MAGELICIOUS_DIR>/etc/di.xml, as follows:

<type name="Magento\Framework\Console\CommandListInterface">
<arguments>
<argument name="commands" xsi:type="array">
<item name="runStockImport" xsi:type="object">Magelicious\Core\Console\Command\RunStockImportCommand</item>
</argument>
</arguments>
</type>

We can now clear the cache and the compiled directories either by running the php bin/magento cache:clean config followed by php bin/magento setup:di:compile, or by running rm -rf generated/* and rm -rf var/cache/*.

Now, if we run the php bin/magento command, we should see our command on the list:

magelicious
magelicious:stock:import The Magelicious Stock Import.

If we now test our method by running php bin/magento magelicious:stock:import, this should immediately trigger an error, as follows:


[Symfony\Component\Console\Exception\RuntimeException]
Not enough arguments (missing: "order_id").

magelicious:stock:import [--days_back [DAYS_BACK]] [--] <order_id>

Either of the following calls should work:

php bin/magento magelicious:stock:import 000000060
php bin/magento magelicious:stock:import 000000060 --days_back=7
You have been reading a chapter from
Magento 2 Development Quick Start Guide
Published in: Sep 2018
Publisher: Packt
ISBN-13: 9781789343441
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image