thinkphp8 定时任务 addArgument

发布于:2024-08-22 ⋅ 阅读:(24) ⋅ 点赞:(0)

在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


网站公告

今日签到

点亮在社区的每一天
去签到