第 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 个方法:
-
configure()
方法用于设置magento 2 add命令行的名称、描述、命令行参数 -
execute()
当我们通过控制台调用此命令行时,方法将运行。
声明此类后,请刷新 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"
以检查结果。