Paginating long lists in the CakePHP Console

I’ve recently been doing some work on some CLI tools, and I came across the need to “paginate” a long list of file. Instead of dumping out 40+ items to the screen all at once, which would be confusing and hard to read, I wanted a more elegant way of showing only a section on the huge list at once. Now this isn’t true pagination unfortunately as PHP doesn’t really support things like framebuffers and instead just writes directly to stdout. But it is an easy to use approach to only showing a slice of a big list at a time.

Show Plain Text
  1. protected function _paginate($list) {
  2.     if (count($list) > 20) {
  3.         $chunks = array_chunk($list, 10);
  4.         $chunkCount = count($chunks);
  5.         $this->out(implode("\n", array_shift($chunks)));
  6.         $chunkCount--;
  7.         while ($chunkCount && null == $this->in('Press <return> to see next 10 files')) {
  8.             $this->out(implode("\n", array_shift($chunks)));
  9.             $chunkCount--;
  10.         }
  11.     } else {
  12.         $this->out(implode("\n", $list));
  13.     }
  14. }

So there you go, a nice simple easy to use method for “pagination” in CLI environments. I’m sure there are a few improvements that could be made to make it function more like Controller::paginate(). But for the time being this solved my problems.

Comments

Where $files comes from?

By the way, very nice way to paginate in CLI.

Renan Gonçalves on 1/16/09

Thanks renan, its been fixed. Yet another reason to not refactor code while writing the post about it.

mark story on 1/16/09

Comments are not open at this time.