hyperf中如何使用command命令行

发布时间:2021-12-28 11:16:38 阅读:2696次

如果使用过laravelthinkphp的话

应该知道可以创建command,也就是可以在cli模式下运行的程序

那么在hyperf中如何实现呢

1、安装composer require hyperf/command

2、执行命令生成

php bin/hyperf.php gen:command FooCommand

3、打开文件app/Command/FooCommand.php

<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Command\Command as HyperfCommand;
use Hyperf\Command\Annotation\Command;
use Symfony\Component\Console\Input\InputArgument;
use Psr\Container\ContainerInterface;

/**
 * @Command
 */
#[Command]
class FooCommand extends HyperfCommand
{
    /**
     * @var ContainerInterface
     */
    protected $container;
    protected $name = 'demo:command';
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;

        parent::__construct('demo:command');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('Hyperf Demo Command');
    }

    public function handle()
    {
        echo __method__;
        // 从 $input 获取 name 参数
        $argument = $this->input->getArgument('name') ?? 'World';
        $this->line('Hello ' . $argument, 'info');
        $this->line('Hello Hyperf!', 'info');
    }

    protected function getArguments()
    {
        return [
            ['name', InputArgument::OPTIONAL, '这里是对这个参数的解释']
        ];
    }
}

4、执行命令php bin/hyperf.php demo:command

5、结果如下

[root@iZbp13ph356ra22ldly01lZ hyperf-skeleton]# php bin/hyperf.php demo:command hellotheworld
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\Config\Listener\RegisterPropertyHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\ExceptionHandler\Listener\ExceptionHandlerListener listener.
[DEBUG] Event Hyperf\Framework\Event\BootApplication handled by Hyperf\DbConnection\Listener\RegisterConnectionResolverListener listener.
App\Command\FooCommand::handle
Hello hellotheworld
Hello Hyperf!

如有问题,可以QQ搜索群1028468525加入群聊,欢迎一起研究技术

支付宝 微信

有疑问联系站长,请联系QQ:QQ咨询
下一篇:hyperf创建task

转载请注明:hyperf中如何使用command命令行 出自老鄢博客 | 欢迎分享