Magento 2/Adobe Commerce is a powerful e-commerce platform that offers flexibility and scalability for online stores. One of its standout features is the Command Line Interface (CLI), which allows developers to perform various tasks efficiently. In this blog, we’ll walk you through the process of creating custom CLI commands in Magento 2. Whether you’re a beginner or an experienced developer, this guide will help you understand the process with a real-world example.
Why Create Custom CLI Commands in Magento 2?
CLI commands are incredibly useful for automating repetitive tasks, performing bulk operations, or integrating with third-party systems. For example, you might want to create a custom command to:
- Generate reports or send notifications.
- Import/export data in a specific format.
- Clear temporary files or cache for specific modules.
Step 1: Create a New Magento 2 Module
Every custom CLI command in Magento 2 is part of a module. If you don’t already have a custom module, let’s create one.
Inside the module directory, create the following files and folders:
app/code/Jigar/CustomModule/
├── etc/
│ └── module.xml
├── registration.php
└── Console/
└── Command/
└── CustomCommand.php
Step 2: Create the Custom CLI Command
Now, let’s create the custom CLI command. In this example, we’ll create a command that displays a simple “Hello, Magento!” message.
- Navigate to the
Console/Command
directory in your module. - Create a file named
CustomCommand.php
:
<?php
namespace Jigar\CustomModule\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class CustomCommand extends Command
{
protected function configure()
{
$this->setName('magento:hello')
->setDescription('Displays a welcome message.');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('Hello, Magento!');
}
}
configure()
Method: This method defines the command name (magento:hello
) and its description.execute()
Method: This method contains the logic that runs when the command is executed. In this case, it simply outputs “Hello, Magento!”.
Step 3: Register the Command
To make Magento aware of your custom command, you need to register it in the di.xml
file.
- Create a
di.xml
file in theetc
directory of your module:
<?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="custom_command" xsi:type="object">Jigar\CustomModule\Console\Command\CustomCommand</item>
</argument>
</arguments>
</type>
</config>
Step 4: Enable the Module and Test the Command
- Run the following commands to enable your module and check if the command works:
php bin/magento setup:upgrade
php bin/magento magento:hello
- If everything is set up correctly, you should see the output:
Hello, Magento!
Real World Example
<?php
namespace Jigar\CustomModule\Console\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\Framework\File\Csv;
use Magento\Framework\Filesystem;
class GenerateLowStockCsv extends Command
{
protected $productCollectionFactory;
protected $csvProcessor;
protected $directoryList;
protected $filesystem;
public function __construct(
CollectionFactory $productCollectionFactory,
Csv $csvProcessor,
DirectoryList $directoryList,
Filesystem $filesystem
) {
$this->productCollectionFactory = $productCollectionFactory;
$this->csvProcessor = $csvProcessor;
$this->directoryList = $directoryList;
$this->filesystem = $filesystem;
parent::__construct();
}
protected function configure()
{
$this->setName('magento:generate-low-stock-csv')
->setDescription('Generates a CSV file of low-stock products.');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
// Define the low-stock threshold
$lowStockThreshold = 10;
// Get product collection with low stock
$productCollection = $this->productCollectionFactory->create();
$productCollection->addAttributeToSelect(['name', 'sku']);
$productCollection->joinField(
'qty',
'cataloginventory_stock_item',
'qty',
'product_id=entity_id'
);
// Now filter the collection based on the quantity
$productCollection->addFieldToFilter('qty', ['lt' => $lowStockThreshold]);
// Prepare CSV data
$csvData = [];
$csvData[] = ['SKU', 'Product Name', 'Stock Qty']; // CSV header
foreach ($productCollection as $product) {
$csvData[] = [
$product->getSku(),
$product->getName(),
$product->getQty()
];
}
// Define the file path
$varDirectory = $this->filesystem->getDirectoryWrite(DirectoryList::VAR_DIR);
$filePath = 'export/low_stock_products_' . date('Ymd_His') . '.csv';
// Write data to CSV file
$this->csvProcessor->saveData($varDirectory->getAbsolutePath($filePath), $csvData);
$output->writeln("CSV file generated successfully: " . $filePath);
}
}
Output :
CSV file generated successfully: export/low_stock_products_20231025_123456.csv
Navigate to the var/export
directory to find the generated CSV file.
Creating a custom CLI command in Magento 2 to generate a CSV of low-stock products is a powerful way to manage inventory efficiently. This command can be scheduled to run periodically, ensuring you always have up-to-date information about your stock levels.
Conclusion
Creating custom CLI commands in Magento 2 is a powerful way to automate tasks and improve efficiency. By following this guide, you can create your own commands tailored to your store’s needs
Feel free to leave a comment if you have any questions or need further assistance. Don’t forget to share this blog with your fellow Magento developers!
Source : https://developer.adobe.com/commerce/php/development/cli-commands/custom/
You may also like,
How to Use ViewModel in Magento 2: A Simple Guide
Leave a Comment