在ThinkPHP8中,我们可以使用addArgument
方法来添加命令行参数。这个方法允许我们定义命令行参数,并且可以指定参数的模式(例如:是否必须,是否可选)。
以下是一个简单的例子,演示如何在ThinkPHP8的命令行中添加一个参数:
<?php
namespace app\command;use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;class Hello extends Command
{protected function configure(){$this->setName('hello')->addArgument('name', Argument::OPTIONAL, "your name")->addOption('city', null, Option::VALUE_REQUIRED, 'city name')->setDescription('Say Hello');}protected function execute(Input $input, Output $output){$name = trim($input->getArgument('name'));$name = $name ?: 'thinkphp';if ($input->hasOption('city')) {$city = PHP_EOL . 'From ' . $input->getOption('city');} else {$city = '';}$output->writeln("Hello," . $name . '!' . $city);}
}
这个文件定义了一个叫hello
的命令,并设置了一个name
参数和一个city
选项。
// 无需任何参数
php think hello
// 输出默认: Hello thinkphp!// 添加命令参数
php think hello kancloud
// 输出: Hello kancloud!// 添加city选项
php think hello kancloud --city shanghai
// 输出: Hello kancloud!From shanghai