【问题标题】:Creating Custom CLI Commands In Magento 2 thows me Error在 Magento 2 中创建自定义 CLI 命令让我出错
【发布时间】:2025-12-07 08:25:01
【问题描述】:

我是 Magento 2 的新手,我正在创建一个打印 hello world 的自定义 CLI 命令,但是当我看到列表 php bin/magento list 时,它没有显示我添加的命令,而是向我抛出了这个错误:

 [Symfony\Component\Console\Exception\CommandNotFoundException]  
  There are no commands defined in the "training" namespace.  

这是我为使 CLI 命令正常工作所做的事情,我不认为我错过了一些东西:

app/code/SimplifiedMagento/FirstModule/Console/Command/HelloWorld.php

<?php


namespace SimplifiedMagento\FirstModule\Console\Command;

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



class HelloWorld extends Command
{
    public function  configure()
    {
        $this->setName("training:hello_world");
        $this->setDescription("the command prints out hello world");
        parent::configure();

    }

    public function execute(InputInterface $input, OutputInterface $output)
    {
        $output->writeln('Hello World');
    }
}

app/code/SimplifiedMagento/FirstModule/etc/frontend/di.xml

<type name="Magento\Framework\Console\CommandList">
                <arguments>
                        <argument name="commands" xsi:type="array">
                                <item name="hello_world" xsi:type="object">
                                        SimplifiedMagento\FirstModule\Console\Command\HelloWorld</item>
                        </argument>
                </arguments>
        </type>

我不知道哪里出错了,谁能帮帮我?

我的命令基本上会说training:hello_world

【问题讨论】:

    标签: php magento2


    【解决方案1】:

    经过一番研究,我发现我必须在我的 etc 文件夹中创建一个单独的 di.xml 文件,而不是 etc/frontend/di.xml

    我已经剪切了命令的di.xml文件的代码,并在etc文件夹中创建了一个新的文件di.xml文件并保留它并且它可以工作。

    <type name="Magento\Framework\Console\CommandList">
                    <arguments>
                            <argument name="commands" xsi:type="array">
                                    <item name="hello_world" xsi:type="object">
                                            SimplifiedMagento\FirstModule\Console\Command\HelloWorld</item>
                            </argument>
                    </arguments>
            </type>
    

    【讨论】: