magento2 控制台 CLI 中添加自定义命令行

第 1 步:在 di.xml 中定义命令

di.xml文件中,您可以使用带名称的类型Magento\Framework\Console\CommandList来定义命令选项。

文件:app/code/Mageplaza/HelloWorld/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="exampleSayHello" xsi:type="object">Mageplaza\HelloWorld\Console\Sayhello</item>
           </argument>
       </arguments>
   </type>
</config>

此配置将声明一个命令类Sayhello。此类将定义该命令的命令名称和execute()方法。

第二步:创建命令类

按照 di.xml 中的定义,我们将创建一个命令类:

文件:app/code/Mageplaza/HelloWorld/Console/Sayhello.php

<?php
namespace Mageplaza\HelloWorld\Console;

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

class Sayhello extends Command
{
   protected function configure()
   {
       $this->setName('example:sayhello');
       $this->setDescription('Demo command line');

       parent::configure();
   }
   protected function execute(InputInterface $input, OutputInterface $output)
   {
       $output->writeln("Hello World");
   }
}

在这个函数中,我们将定义 2 个方法:

声明此类后,请刷新 Magento 缓存并键入以下命令:

php magento --list

您将看到所有命令的列表。我们的命令将在这里显示

[图片上传失败...(image-6ea63d-1654135385271)]

现在您可以bin/magento example:sayhello从命令运行以查看结果

[图片上传失败...(image-9f1b73-1654135385271)]

现在,我们将为命令添加参数。

内容将是:

<?php

namespace Mageplaza\HelloWorld\Console;

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

class Sayhello extends Command
{

    const NAME = 'name';

    protected function configure()
    {

        $options = [
            new InputOption(
                self::NAME,
                null,
                InputOption::VALUE_REQUIRED,
                'Name'
            )
        ];

        $this->setName('example:sayhello')
            ->setDescription('Demo command line')
            ->setDefinition($options);

        parent::configure();
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        if ($name = $input->getOption(self::NAME)) {

            $output->writeln("Hello " . $name);

        } else {

            $output->writeln("Hello World");

        }

        return $this;

    }
}

我们在函数name中为命令行定义了参数并在configure()函数中获取它execute()。请清除缓存并从命令行运行php bin/magento example:sayhello --name="Join"以检查结果。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容