Hyperf 的命令行默认由 hyperf/command 组件提供,而该组件本身也是基于 symfony/console 的抽象。
一、安装
-  
通常来说该组件会默认存在,但如果您希望用于非 Hyperf 项目,也可通过下面的命令依赖 hyperf/command 组件。
composer require hyperf/command 
二、生成命令
-  
如果你有安装 hyperf/devtool 组件的话,可以通过
gen:command命令来生成一个自定义命令。 -  
生成文件:app\Command\FooCommand.php
php bin/hyperf.php gen:command FooCommand 
三、类文件内容
<?php
namespace App\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;
use Symfony\Component\Console\Input\InputArgument;
// 通过注解 Command 定义
#[Command]
class FooCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        // 参加为执行命令
        parent::__construct('foo:test');
    }
    public function configure()
    {
        parent::configure();
        $this->setDescription('Hyperf Demo Command');
        // 定义命令 中的 name参数
        $this->addArgument('name', InputArgument::OPTIONAL, '这是name参数', 'guanyuyan');
    }
    public function handle()
    {
        // 取命令行中 传入的 name参数
        $name = $this->input->getArgument('name');
        $this->line(sprintf('Hello %s!', $name), 'info');
    }
}
 
四、使用
php bin/hyperf.php foo:test name:abc
 




















