如何在Magento 2中将命令行添加到控制台CLI中

在本文中,我们将了解如何在magento 2控制台CLI中添加命令行Magento 2添加命令行使用界面快速更改一些功能,如:

  • 安装Magento(以及相关任务,例如创建或更新数据库模式,创建部署配置等)
  • 清除缓存
  • 管理索引,包括重建索引
  • 创建翻译词典和翻译包
  • 为插件生成不存在的类(如工厂和拦截器),为对象管理器生成依赖项注入配置
  • 部署静态视图文件
  • 从LESS创建CSS

在开始之前,请花几分钟时间了解Magento 2 CLI中的命名。

我们将使用示例模块Mageplaza_HelloWorld演示本课程。要向Magento 2 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()方法。

第2步:创建命令类

在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()method用于设置magento 2 add 命令行的名称,描述,命令行参数
  • execute() 当我们通过控制台调用此命令行时,将运行该方法。

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

php magento --list

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

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

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

内容将是:

<?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;

	}
}

我们nameconfigure()函数中为命令行定义了参数并将其置于execute()函数中。请清除缓存并从命令行运行php bin/magento example:sayhello --name="Join"以检查结果。它将显示“你好加入”

赞(1)
微信
支付宝
微信二维码图片

微信扫描二维码打赏

支付宝二维码图片

支付宝扫描二维码打赏

相关文章

0 0 投票数
文章评分
订阅评论
提醒
0 评论
内联反馈
查看所有评论