本文讨论如何添加控制台命令。Magento 2 使用命令行可以快速实现一些操作:
- 安装 Magento (相关的还有创建、更新数据表,添加或发布配置文件等)
- 清缓存
- 管理索引,重建索引
- 创建翻译文件及语言包
- 生成不存在的一些类如工厂类和插件的拦截器,为对像管理器生成依赖注入配置文件
- 发布静态文件
- 编译LESS到CSS
开始之前确保 HelloWorld 模块还在,这个模块在前面章节也一直使用。下面开始添加我们自定义的命令:
第一步:在 di.xml 定义命令
在 di.xml 文件中可以使用 name 属性为 Magento\Framework\Console\CommandList
的 type 节点定义命令参数。
文件: app/code/Aqrun/HelloWorld/etc/di.xml
<type name="Magento\Framework\Console\CommandList">
<arguments>
<argument name="commands" xsi:type="array">
<item name="exampleSayHello" xsi:type="object">Aqrun\HelloWorld\Console\Sayhello</item>
</argument>
</arguments>
</type>
代码中定义了一个命令类 Sayhello。命令类中会定义命令行名称,并实现 execute()
方法
第二步:创建命令类
根据配置文件我们创建如下类
文件: app/code/Aqrun/HelloWorld/Console/Sayhello.php
<?php
namespace Aqrun\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('示例:sayhello');
$this->setDiscription('示例命令');
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln('你好世界');
}
}
函数中实现了两个方法:
- configure() 函数用来设置名称、描述、命令行参数
- execute() 函数会在控制台调用命令时执行
类的定义完成后清空缓存,执行如下命令:
php magento list
可以输出所有可用命令,我们刚添加的自定义命令也在:
现在可以在控制台运行 php bin/magento example:sayhello
:
接下来可以给命令添加一些参数。
代码如下:
<?php
namespace Aqrun\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, '姓名')
];
$this->setName('example:sayhello')
->setDescription('示例命令')
->setDefinition($options);
parent::configure();
}
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($name = $input->getOption(self::NAME)) {
$output->writeln('你好' . $name);
} else {
$output->writeln('你好世界');
}
}
}
代码中我们在 configure() 函数中定义了命令行参数 name,并在 execute() 方法中获取它的值。清空缓存然后运行 php bin/magento example:sayhello --name=Aqrun
就会输出 “你好Aqrun”。