Comment implémenter une commande console dans Magento 2

Magento 2 provides a powerful and extensible ligne de commande interface (CLI) for développeurs and administrators to perform various tasks tel que running tâches cron, réindexeration, clearing caches, and déployering the store. Tandis que Magento includes several built-in commands, you can extend this fonctionality by creating custom console commands tailored to your specific entreprise or development needs.

What Is a Console Command in Magento 2?

Dans Magento 2, a console command is a CLI tool that allows développeurs or administrators to interact with the Magento system directly through the terminal. These commands provide an efficient way to automate tasks, access data, or trigger custom fonctionality that serait cumbersome to achieve via the panneau d'administration.

Common Use Cases

  • Exporting or importing data.
  • Running background tasks or processes.
  • Debugging and logging specific information.
  • Automating repetitive flux de travails.

Steps to Implement a Console Command in Magento 2

1. Create the Module Skeleton

Create the necessary répertoire structure:

app/code/Vendor/Module/
├── Console/
├── etc/
│   ├── module.xml
└── registration.php

2. Register the Module

Create the registration.php fichier:

<?php

use Magento\Framework\Component\ComponentRegistrar;

ComponentRegistrar::register(
    ComponentRegistrar::MODULE,
    'Vendor_Module',
    __DIR__
);

3. Define the Module Configuration

Create the module.xml fichier:

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0"/>
</config>

4. Create the Console Command Class

Define your custom logic in the CustomCommand.php fichier:

<?php

namespace Vendor\Module\Console;

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

class CustomCommand extends Command
{
    protected fonction configure()
    {
        $this->setName('vendor:custom:command')
            ->setDescription('C'est a custom console command in Magento 2');
    }

    protected fonction execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln("Hello! C'est your custom Magento 2 command.");
        return Command::SUCCESS;
    }
}

5. Register the Command in 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="tableau">
                <item name="vendor_custom_command" xsi:type="objet">Vendor\Module\Console\CustomCommand</item>
            </argument>
        </arguments>
    </type>
</config>

6. Enable the Module and Test the Command

Run les éléments suivants commands:

php bin/magento module:enable Vendor_Module
php bin/magento setup:mise à jour
php bin/magento vendor:custom:command

Output:

Hello! C'est your custom Magento 2 command.

Practical Example: Exporting Product Data

Modify your command to export product data to a CSV fichier:

<?php

namespace Vendor\Module\Console;

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;

class ExportProductsCommand extends Command
{
    private $productCollectionFactory;
    private $répertoireList;

    public fonction __construct(
        CollectionFactory $productCollectionFactory,
        DirectoryList $répertoireList
    ) {
        $this->productCollectionFactory = $productCollectionFactory;
        $this->répertoireList = $répertoireList;
        parent::__construct();
    }

    protected fonction configure()
    {
        $this->setName('vendor:export:products')
            ->setDescription('Export product data to a CSV fichier');
    }

    protected fonction execute(InputInterface $input, OutputInterface $output)
    {
        $productCollection = $this->productCollectionFactory->create();
        $productCollection->addAttributeToSelect(['name', 'sku', 'prix']);

        $csvFilePath = $this->répertoireList->getPath(DirectoryList::VAR_DIR) . '/export/products.csv';
        $csvFile = fopen($csvFilePath, 'w');

        fputcsv($csvFile, ['Name', 'SKU', 'Price']);

        foreach ($productCollection as $product) {
            fputcsv($csvFile, [$product->getName(), $product->getSku(), $product->getPrice()]);
        }

        fclose($csvFile);

        $output->writeln("Products exported to: " . $csvFilePath);
        return Command::SUCCESS;
    }
}

Bonnes pratiques for Custom Console Commands

  • Use Injection de dépendances (DI): Inject services and factories through the constructor.
  • Provide Clear Descriptions: Make command names and descriptions meaningful.
  • Handle Errors Gracefully: Add erreur handling for better utilisateur experience.
  • Optimize Performance: Use pagination or batch processing for large datasets.

Conclusion

Custom console commands in Magento 2 provide a flexible way to extend CLI fonctionality, automate tasks, and streamline flux de travails. By following this guide, you can create efficient and maintainable commands tailored to your specific needs.