17、Hyperf 3 快速使用 - 命令行操作

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 461

时间: 2023-04-25 12:35:42

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握自定义命令的使用

快速使用自定义命令行

第一步:创建 command

php bin/hyperf.php gen:command TestCommand

访命令会在 app/Commadn 目录下生成 TestCommand.php 文件,内容如下:

<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Psr\Container\ContainerInterface;

#[Command]
class TestCommand extends HyperfCommand
{
    public function __construct(protected ContainerInterface $container)
    {
        // 定义执行命令
        parent::__construct('test:test');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('测试命令操作');
    }

    public function handle()
    {
        // 业务逻辑处理
        
        // 通过内置方法 line 在 Console 输出 Hello Hyperf.
        $this->line('hi,我是一个命令操作哟~', 'info');
    }
}

查看命令

php bin/hyperf.php | grep test
 test
  test:test           测试命令操作

第二步:执行命令

php bin/hyperf.php test:test

详解学习

定义命令参数

在编写命令时,通常是通过 参数选项 来收集用户的输入的,在收集一个用户输入前,必须对该 参数选项 进行定义。

案例:假设我们希望定义一个 name 参数,然后通过传递任意字符串如 Hyperf 于命令一起并执行 php bin/hyperf.php test:test 王美丽

use use Symfony\Component\Console\Input\InputArgument;

public function handle()
{
    // 接收参数
    $name = $this->input->getArgument('name') ?? '';

    $this->line( $name . ' 世界之旅', 'info');
}

// 定义参数
protected function getArguments()
{
    return [
        // 定义一个 name 参数】
        // 格式:[参数名, '对参数名的说明']
        ['name', InputArgument::OPTIONAL, '这里是对这个参数的解释']
    ];
}

常用配置学习

Help 帮助信息

public function configure()
{
    parent::configure();
    $this->setHelp('命令演示');
}

效果:

$ php bin/hyperf.php test:test --help
...
Help:
  命令演示

设置 Description

对这个命令进行说明

public function configure()
{
    parent::configure();
    $this->setDescription('测试命令操作');
    $this->setHelp('命令演示');
}

效果

$ php bin/hyperf.php test:test --help
...
Description:
  测试命令操作

设置 Usage

public function configure()
{
    parent::configure();
    // 添加一个命令使用示例,它将以命令名作为前缀。
    $this->addUsage('--name 用户姓名');
}

效果

$ php bin/hyperf.php test:test --help
    
Usage:
  test:test [options] [--] [<name>]
  test:test --name 用户姓名

设置参数

参数支持以下模式。

模式 备注
InputArgument::REQUIRED 1 参数必填,此种模式 default 字段无效
InputArgument::OPTIONAL 2 参数可选,常配合 default 使用
InputArgument::IS_ARRAY 4 数组类型
public function configure()
{
    parent::configure();
    $this->setDescription('测试命令操作');
    $this->setHelp('命令演示');
    $this->addUsage('--name 用户姓名');
    
    // 设置命令参数
    $this->addArgument('name', InputArgument::OPTIONAL, '姓名', '王美丽');
}

设置选项

选项支持以下模式。

模式 备注
InputOption::VALUE_NONE 1 是否传入可选项 default 字段无效
InputOption::VALUE_REQUIRED 2 选项必填
InputOption::VALUE_OPTIONAL 4 选项可选
InputOption::VALUE_IS_ARRAY 8 选项数组
public function configure()
{
    parent::configure();
    $this->addOption('name','o', InputOption::VALUE_NONE, '用户名');
}

效果

$ php bin/hyperf.php test:test -o
    
王美丽 世界之旅
请登录后再评论