TP6.0命令行之自定义指令
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);
}
本站发布的内容若侵犯到您的权益,请邮件联系站长删除,我们将及时处理!
从您进入本站开始,已表示您已同意接受本站【免责声明】中的一切条款!
本站大部分下载资源收集于网络,不保证其完整性以及安全性,请下载后自行研究。
本站资源仅供学习和交流使用,版权归原作者所有,请勿商业运营、违法使用和传播!请在下载后24小时之内自觉删除。
若作商业用途,请购买正版,由于未及时购买和付费发生的侵权行为,使用者自行承担,概与本站无关。