Symfony console commands are widely used for tasks that involve tracking progress over time - such as processing large datasets, importing records, or running batch jobs. In these cases, a single progress bar is sometimes not enough. We may want to visualize multiple dimensions of progress at once, for example tracking items inside batches, or steps inside stages. Symfony Console component makes this possible by using output sections, which allow multiple progress bars to be rendered simultaneously and updated independently. This tutorial shows how to display multiple progress bars in console command in Symfony 8 application.
Symfony provides the section method in the output instance, which creates isolated output areas in the terminal. Each progress bar can be attached to its own section, allowing Symfony to redraw them without interfering with one another.
Consider a command that processes data in batches. We might want:
- One progress bar to represent the total number of processed items.
- Another progress bar to show how many batches have been completed.
Showing both gives clearer feedback to the user and makes long-running commands easier to monitor.
Below is a simple example command that displays two progress bars: one for individual items and one for batches.
src/Command/TestCommand.php
<?php
namespace App\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Helper\ProgressBar;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name: 'app:test')]
class TestCommand extends Command
{
protected function execute(InputInterface $input, OutputInterface $output): int
{
$itemsBar = new ProgressBar($output->section(), 100);
$itemsBar->setFormat('Items : %current%/%max% [%bar%] %percent:3s%%');
$batchesBar = new ProgressBar($output->section(), 10);
$batchesBar->setFormat('Batches : %current%/%max% [%bar%] %percent:3s%%');
$itemsBar->start();
$batchesBar->start();
for ($i = 0; $i < 100; ++$i) {
$itemsBar->advance();
if ($i % 10 === 0) {
$batchesBar->advance();
}
usleep(50000);
}
return self::SUCCESS;
}
}
Leave a Comment
Cancel reply