How To Add A Progress Bar In CLI Command
We assume that you have already created several custom CLI commands for your Magento project to execute processes that you may need. In this post we will see together how you can add a progress bar to that CLI command. Let's go then!
First of all we will define our CLI command in the di.xml and also configure the command's name via constructor $name argument like you see below.
Afterward in our class ProgressBarCommand we created the execute function that will be called from our CLI command. As you see in the constructor and using Magento dependency injection feature, we inject the classes that we will need in out example. And this are the ProgressBarFactory and the county CollectionFactory. As is well known Magento uses the Symfony's console command and additionaly related packages like the Symfony\Component\Console\Helper\ProgressBar, which we will use and you can find more information here.
As you can see in our example below, the creation of an instance of the ProgressBar class requires 2 variables, the $output and a number of units for the progress bar. In our case we will use as example the country collection, where the total amount of the countries in Magento will be set as the amount of units. That will be in total of 249 units. Then we set a custom format for our progress bar which is a string that contains specific placeholders. Here you can see the a list of the built-in placeholders. In our case we will use the placeholders, current, max, bar, percent, elapsed and memeory. Then we start and display the progress bar by calling $progressBar->start(). As you see afterwards we loop through all countries and we advances the progress bar 1 unit every time by calling $progressBar->advance(). You can also advances the progress bar by more that 1 unit every time like $progressBar->advance(10). Last step is to finish the progress bar outside the loop, by calling $progressBar->finish(). That ensures that the progress bar is at 100%.
The output in terminal after executing the command php bin/magento magevision:blog63:progress-bar will be the following.
The full example as extension can be found here.
Feel free to share this post and ask your questions in the comments below.
Till next time!