Cover of the book Symfony 5: The Fast Track

Symfony 5: The Fast Track is the best book to learn modern Symfony development, from zero to production. +300 pages showcasing Symfony with Docker, APIs, queues & async tasks, Webpack, SPAs, etc.

New in Symfony 4.3: Iterable progress bars

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.

Contributed by
Jérôme Vasseur
in #29753.

The common workflow for Symfony Console progress bars is to start them, advance them according to your task progress and finish them:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
use Symfony\Component\Console\Helper\ProgressBar;

$progressBar = new ProgressBar($output);
$progressBar->start();

// ... do some work
$progressBar->advance();

// needed to ensure that the bar reaches 100%
$progressBar->finish();

In Symfony 4.3 we've improved this workflow when you work with iterable variables (such as arrays or generators). Thanks to the new iterate() method, you can pass the iterable variable and the progress bar starts, advances and finishes automatically.

Consider the following simple PHP generator:

1
2
3
4
5
$iterable = function () {
    yield 1;
    yield 2;
    // ...
};

You can turn this into a progress bar as follows:

1
2
3
4
5
6
7
use Symfony\Component\Console\Helper\ProgressBar;

$progressBar = new ProgressBar($output);

foreach ($progressBar->iterate($iterable) as $value) {
    // ... do some work
}

The output in your terminal will be the following:

1
2
3
0 [>---------------------------]
1 [==============>-------------]
2 [============================]

If the iterable variable is countable, the max steps of the progress bar is set automatically. Otherwise, you can pass the number of steps as the second optional argument of iterate():

1
2
3
foreach ($progressBar->iterate($iterable, 100) as $value) {
    // ... do some work
}
Help the Symfony project!

As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.

Comments

A Generator that you pass to iterate() is not countable. So the ProgressBar does not know automatically that there will be maximum of two items. The given output does not fit with an indeterminate progress bar. Alternatively you can use `$progressBar->iterate($iterable, 2)`
Very nice, this makes the flow much clear!
@Tobias thanks for your comment. I've updated the post to fix the progress bar output error and to mention the countable behavior.

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.