symfony - 缺少控制台命令参数时显示问题
问题描述
我正在 Symfony 中编写控制台命令。
当用户没有指定名称参数时,我不明白是否可以显示我添加的问题(你想问候谁?)。
class GreetCommand extends Command
{
// ...
protected function configure()
{
$this
->setName('greet:someone')
->setDescription('Greet somebody')
->addArgument('name', InputArgument::REQUIRED, 'Who do you want to greet?')
;
}
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$year = $input->getArgument('name');
...
目前,如果我运行bin/console greet:someone命令,我会收到以下错误:
没有足够的参数(缺少:“名称”)。
问候某人
解决方案
Symfony Style 对象可以帮助你做到这一点。
首先将您的参数更改为可选而不是必需。
protected function configure()
{
$this
->setName('greet:someone')
->setDescription('Greet somebody')
->addArgument('name', InputArgument::OPTIONAL, 'Who do you want to greet?')
;
}
然后你可以使用 SymfonyStyle 对象来帮助你交互式地问问题:
// Use this method to instantiate a SymfonyStyle
protected function initialize(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$name = $input->getArgument('name');
if (!$name) {
$name = $this->io->ask('Who do you want to greet?');
}
...
ask 方法采用第二个参数为 name 提供默认值,并采用第三个参数来验证用户输入是否具有可调用性。它们都是可选的。
https://symfony.com/doc/current/console/style.html#user-input-methods
推荐阅读
- bash - SH - 用变量替换文本值中的单词
- simulation - Webots 中的吸盘模拟
- json - 将txt转换为json文件
- python - 为什么每个 GPU 上都显示单个 pytorch 进程
- c++ - Visual Studio 非 vcxproj 标头仅包含在代码分析中
- distributed - Raft Leader 选举,当candidater 收到带有 Higher Term 的 voteRequest 时,candidater 应该怎么做?
- django - 如何在 django Rest Framework 中从 view.py 提供 SerializerMethodField 输入
- visual-studio - Unity WebGL - 有没有办法清除构建时的所有错误?
- reactjs - 反应本机博览会 api 发布问题
- javascript - 如何在 react-bootstrap 中打开不同的折叠按钮?