进度指示器
进度指示器用于告知用户命令没有停滞。与 进度条 不同,这些指示器用于命令持续时间不确定的情况(例如,长时间运行的命令、无法量化的任务等)。
它们通过实例化 ProgressIndicator 类并在命令执行时推进进度来工作。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
use Symfony\Component\Console\Helper\ProgressIndicator;
// creates a new progress indicator
$progressIndicator = new ProgressIndicator($output);
// starts and displays the progress indicator with a custom message
$progressIndicator->start('Processing...');
$i = 0;
while ($i++ < 50) {
// ... do some work
// advances the progress indicator
$progressIndicator->advance();
}
// ensures that the progress indicator shows a final message
$progressIndicator->finish('Finished');
自定义进度指示器
内置格式
默认情况下,进度指示器上呈现的信息取决于 OutputInterface
实例的当前详细程度。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# OutputInterface::VERBOSITY_NORMAL (CLI with no verbosity flag)
\ Processing...
| Processing...
/ Processing...
- Processing...
✔ Finished
# OutputInterface::VERBOSITY_VERBOSE (-v)
\ Processing... (1 sec)
| Processing... (1 sec)
/ Processing... (1 sec)
- Processing... (1 sec)
✔ Finished (1 sec)
# OutputInterface::VERBOSITY_VERY_VERBOSE (-vv) and OutputInterface::VERBOSITY_DEBUG (-vvv)
\ Processing... (1 sec, 6.0 MiB)
| Processing... (1 sec, 6.0 MiB)
/ Processing... (1 sec, 6.0 MiB)
- Processing... (1 sec, 6.0 MiB)
✔ Finished (1 sec, 6.0 MiB)
提示
使用静默标志 (-q
) 调用命令以不显示任何进度指示器。
除了依赖当前命令的详细模式,您还可以通过 ProgressIndicator
构造函数的第二个参数强制指定格式。
1
$progressIndicator = new ProgressIndicator($output, 'verbose');
内置格式如下:
普通
详细
非常详细
如果您的终端不支持 ANSI,请使用 no_ansi
变体。
普通_无_ANSI
详细_无_ANSI
非常详细_无_ANSI
自定义指示器值
除了使用内置的指示器值,您还可以设置自己的值。
1
$progressIndicator = new ProgressIndicator($output, 'verbose', 100, ['⠏', '⠛', '⠹', '⢸', '⣰', '⣤', '⣆', '⡇']);
进度指示器现在看起来像这样:
1 2 3 4 5
⠏ Processing...
⠛ Processing...
⠹ Processing...
⢸ Processing...
✔ Finished
进度完成后,它会显示一个特殊的完成指示器(默认为 ✔)。您可以将其替换为您自己的。
1 2 3 4 5 6 7 8
$progressIndicator = new ProgressIndicator($output, finishedIndicatorValue: '🎉');
try {
/* do something */
$progressIndicator->finish('Finished');
} catch (\Exception) {
$progressIndicator->finish('Failed', '🚨');
}
进度指示器现在看起来像这样:
1 2 3 4 5
\ Processing...
| Processing...
/ Processing...
- Processing...
🎉 Finished
7.2
构造函数的 finishedIndicator
参数在 Symfony 7.2 中引入。方法 finish()
的 finishedIndicator
参数在 Symfony 7.2 中引入。
自定义占位符
进度指示器使用占位符(用 %
字符括起来的名称)来确定输出格式。以下是内置占位符的列表:
indicator
:当前指示器;elapsed
:自进度指示器启动以来经过的时间;memory
:当前内存使用量;message
:用于在进度指示器中显示任意消息。
例如,这是自定义 message
占位符的方法:
1 2 3 4 5 6 7
ProgressIndicator::setPlaceholderFormatterDefinition(
'message',
static function (ProgressIndicator $progressIndicator): string {
// Return any arbitrary string
return 'My custom message';
}
);
注意
占位符自定义是全局应用的,这意味着在调用 setPlaceholderFormatterDefinition()
之后显示的任何进度指示器都将受到影响。
这项工作,包括代码示例,均根据 Creative Commons BY-SA 3.0 许可获得许可。