Pure PHP: create a progress bar on the command line

Tram Ho

Stumbled across some pretty cool progress bars on nodejs, today I’m going to show you guys how to write a colorful progress bar in php. Create class ProgressBar sql <?php final class ProgressBar { /**Ký tự dùng phần hoàn thành của progress bar */ const FILL_CHAR = "▓"; /**Ký tự dùng phần còn lại chưa hoàn thành của progress bar */ const NOT_FILL_CHAR = "░"; /** Độ dài tối đa của thanh progress bar */ const BAR_LENGTH = 50; /** @var int Số bứớc nhảy tối đa của progress bar, mặc định ban đầu là 0*/ private $maxProcess = 0; /** @var int Bứớc nhảy hiện tại của progress bar, mặc định ban đầu là 0 */ private $currenProcess = 0; /** @var bool Trạng thái kết thúc của thanh tiến trình */ private $endProgress = false; /** @var string Nơi lưu toàn bộ progress bar */ private $progressBar = ""; /** Danh sách màu của progress bar, cái này chỉ để cho thanh progress bar trông màu mè hơn xíu :)) */ private $colors = []; } Tạo constructor để khởi tạo số bước nhảy tối đa của progress bar, tiếp đó là khởi tạo các mã màu để sử dụng cho việc biến đổi màu sắc theo số % của thanh tiến trình. perl public function __construct($max) { $this-> maxProcess = $max; $this->initColorCode(); } private function initColorCode() { for ($i = 196; $i <= 231; $i++) { $this->colors[] = $i; } for ($i = 123; $i >= 119; $i--) { for ($j = 0; $j < 3; $j++) { $this->colors[] = $i - 36 * $ j; } } } Color code constructor %: php private function getColorCode($percent) { $code = floor($percent / 2); if (!isset($this->colors[$code])) { $code = $this->colors[count($this->colors) - 1]; } else { $code = $this->colors[$code]; } return "e[38;5;{$code}m"; } Each time the progress bar changes, the characters previously shown to the console must be replaced, the getBackward function will accept the current % and return the corresponding escape character to relpace the printed characters. previous: perl private function getBackward($percent) { $backward = (strlen($this->progressBar) + 2); if ($percent < 10) { $backward++; } return "�33[{$backward}D "; } Whoa that sounds rambling, where’s my progress bar? Well, I’ll show the main code first, my add-on function will be below and explain later :)) php public function start() { echo "n�33[?25l"; // show break line and hide cursor $this->showProcess(0); } The start function hides the cursor on the console and calls the showProcess function with an initial input of 0% (will be written below) php public function advance($step = 1) { $this->currenProcess += $step; // Each time the function is called, increase the current process by $percent = floor($this->currenProcess * 100 / $this->maxProcess); // calculate the percentage corresponding to the current process $this->showProcess($percent); // call the function to show progress bar if ($percent >= 100 && !$this->endProgress) { // if the percentage is over 100%, mark it as end progress to not increase the length of the progress bar $this->endProgress = true; } } The advance function allows an int parameter to be passed, which is the jump of the progress bar. If not passed, by default, each call will increase the step by 1 unit. php public function __destruct() { $this->endProgress = true; echo "�33[?25hn"; //show cursor and break line } After running, the destructor will be called and display the cursor again. Missing 2 functions createProgress and showProcess, right here :)) perl private function createProgress($percent) { $bar = ''; if ($percent >= 100) { // If the percentage is more than 100, reset it to 100 so as not to increase the length of the progress bar $percent = 100; } $fillPoint = floor($percent / (floor(100 / static::BAR_LENGTH))); // calculate how much % to fill progress bar for ($i = 0; $i < $fillPoint; $i++) { $bar .= static::FILL_CHAR; } $notFill = static::BAR_LENGTH - $fillPoint; // calculate how many % incomplete to fill progress bar for ($i = 0; $i < $notFill - 1; $i++) { $bar .= static::NOT_FILL_CHAR; } return $bar; // return a string of progress bars } private function showProcess($percent) { $backward = $this->getBackward($percent); // get backward code to replace progress bar $bar = $this->createProgress($percent); // create progress bar string $colorCode = $this->getColorCode($percent); // get color code corresponding to current progress bar $total = "{$this->currenProcess}/" . ($this->currenProcess > $this->maxProcess ? $this->currenProcess : $this->maxProcess); // calculate the total number of steps echo $this->progressBar = "{$backward}{$colorCode} {$total} " // show progress bar . Formater::ESCAPE . " [{$colorCode}{$bar}" . Formater::ESCAPE . "] {$colorCode}{$percent} %" . Formater::ESCAPE; } Finally, initialize the ProgressBar instance to test it $command = new Command; $command->progressStart(1000); for($i = 0; $i < 1500; $i++) { $command->progressAdvance(); usleep(50000); // sleep half a second for each step to see the progress bar slowly change :)) } ![](https://images.viblo.asia/7f66d228-e6ea-4922-9fba -8c9ea8031143.gif) Full code [here ](https://github.com/nguyenthemanh2601/pure_php/blob/master/core/Console/ProgressBar.php) Reference color code for console [here](https:/ /misc.flogisoft.com/bash/tip_colors_and_formatting) Thanks for watching ;p

Share the news now

Source : Viblo