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);
}
相关文章
- C/C++ 查找指定文件HEX特征
- C/C++ 遍历进程内存块
- C/C++ 实现模拟键盘鼠标
- C/C++遍历某进程的模块
- C/C++ PeView 结构解析器
- C/C++ 使用 cryptopp 加密解密
- C/C++ 异或加密实现代码
- C/C++ 实现获取Linux系统参数
- C# 通过VMI接口获取硬件ID
- Linux 多种方式实现文件共享
- C/C++ Qt 命令行版网络通信
- C/C++ Qt 基本文件读写方法
- Django 前端BootCSS 实现分页
- Django Ajax 实现历史图形查询
- Django Ajax 实现Web命令行执行
- Django Ajax动态图形监控
- Django 实现统计网站访问状态
- Django Admin后台定制简单监控页
- C/C++ Qt QThread 线程组件应用
- C/C++ Qt QChart 绘图组件应用