如果使用过laravel
和thinkphp
的话
应该知道可以创建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加入群聊,欢迎一起研究技术
转载请注明:hyperf中如何使用command命令行 出自老鄢博客 | 欢迎分享