CakePHP Progress Bar Shell Task

Posted by Matt on Wed, Mar 17 2010

I haven't posted any new code in awhile, so I figured I'd share this simple progress bar I use when running long CakePHP shells.

Get It

The code is available on GitHub.

Progress Bar Pr0n

Here's what it looks like in action:

Usage

1. Include the task in your shell. Even though this is a plugin you don't need to use the "PluginName.TaskName" format. Cake finds it somehow. It's magic.

var $tasks = array('ProgressBar');

2. Before whatever your looping through, start the progress bar by passing in the total number of whatever you're doing.

$this->ProgressBar->start(count($loops));

3. Then each time you go through the loop call next:

$this->ProgressBar->next();

Calling ProgressBar::next() will increment the bar one unit. You can also pass in a value to increment more then one unit. For example is you are processing a file you could pass the total file size in at the start and then for each chunk pass how much you processed.

$this->ProgressBar->next(strlen($chunk));

You can also set the progress bar to any point by calling ProgressBar::set(). This isn't a percentage. It's the "x of total" that is done. So if you set the total to 150 and call set with a parameter of 50 it will show the progress bar as 1/3 done.

$this->ProgressBar->set(50);

Done

This post is now 100% complete.

9 Comments

Graham Weldon said on Mar 18, 2010
Nice work. I can see this being useful for a number of projects already.
Kevin van Zonneveld said on Mar 18, 2010
Heh, great post Matt :) Will try this out soon, looks very good!
Comment 100% complete as well.
Rodrigo Moyle said on Mar 19, 2010
Hey Matt, nice work.

But there is a error, is var $tasks = and not var $task =
Matt said on Mar 19, 2010
Thanks. Fixed
Plastic said on Mar 19, 2010
correcting

public $tasks = array('ProgressBar');

"Cowboy" Ben Alman said on Apr 01, 2010
Needs more peen!

http://peenmeter.com/

:P
Ben Alman said on Apr 01, 2010
Jani Peltoniemi said on Apr 01, 2010
I had no idea that you could do that with \r(although on hindsight it seems pretty obivous).
Thanks for sharing :)
Aaron Shafovaloff said on Jun 08, 2010
ProgressBar seems broken in 1.3.2, with this error showing upon using set or next:

Fatal error: Call to undefined method App::path() in /var/www/cake/libs/i18n.php on line 264

Add new comment