zl程序教程

您现在的位置是:首页 >  其他

当前栏目

TP6.0命令行之自定义指令

2023-02-19 12:20:09 时间

1. 创建自定义指令


一、第一步: 创建自定义命令类文件

命令格式

php think make:command 自定义命令类 命令名

使用示例

php think make:command Hello hello
php think make:command index@Hello hello

自定义命令类方法示例

configure() 方法用于指令的配置: 命令名、参数、选项、描述

execute() 方法在命令行执行指令时会执行

protected function configure()
{
    // 指令配置
    $this->setName('hello')
        ->setDescription('the hello command');
}
protected function execute(Input $input, Output $output)
{
    // 指令输出
    $output->writeln('hello');
}

二、第二步:在 config/console.php 配置文件定义命令

return [
// 指令定义
'commands' => [
'hello' => app\command\Hello::class,
// 'hello' => app\index\command\Hello::class,
],
];

三、在命令行测试运行

php think hello

2. 指令的参数、选项


一句话概括: 参数是必写的,选项的可选的

指令参数

protected function configure()
{
// 指令配置
$this->setName('hello')
// 参数
->addArgument('name', Argument::OPTIONAL, "your name")
->setDescription('Say Hello');
}
protected function execute(Input $input, Output $output)
{
// 获取name参数值
$name = trim($input->getArgument('name'));
$name = $name ?: 'thinkphp';
// 指令输出
$output->writeln("Hello," . $name . '!');
}

指令选项

protected function configure()
{
// 指令配置
$this->setName('hello')
// 选项
->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
->setDescription('Say Hello');
}
protected function execute(Input $input, Output $output)
{
if ($input->hasOption('city')) {
$city = PHP_EOL . 'From ' . $input->getOption('city');
} else {
$city = '无';
}
// 指令输出
$output->writeln("city: " . $city);
}