3 // @role handles paging for large result sets
4 // @author Matt Todd <matt@matttoddphoto.com>
6 // @requires extexception.php (extends ExtException class)
7 // @usage $p = new Pager($rows, $per_page);
12 private $pages = array();
15 // constructor (vital)
16 public function __construct($collection, $per_page) {
17 if(!is_array($collection)) $collection = array();
18 $this->pages
= array_chunk($collection, $per_page);
20 public static function paginate($collection, $per_page) {
21 return new Pager($collection, $per_page);
24 // navigation/iteration functions
25 public function next() {
26 if(!next($this->pages
)) return false;
29 public function previous() {
30 if(!prev($this->pages
)) return false;
33 public function first() {
37 public function last() {
41 public function current() {
42 return current($this->pages
);
44 public function all() {
45 return current($this->pages
);
47 public function page($page = null) {
49 if($page !== null) return $this->pages
[$page - 1];
50 return current($this->pages
);
52 public function all_pages() {
55 public function page_numbers() {
56 for($i = 0; $i < count($this->pages
); $i++
) {
57 $page_numbers[] = $i +
1;
61 public function page_number() {
62 if($this->page
== null) return 1;
67 public function has_next() {
68 // if the page has been set and the next one is set, then there has to be a next page
69 if(!empty($this->page
)) {
70 if(!empty($this->pages
[($this->page
- 1) +
1])) return true; // see note below
72 // NOTE: the page - 1 + 1 is basically
73 // for semantics because the page value
74 // is actually one greater than the actual
75 // page id in the array
77 // skips all this extra complicated crap only if $this->page has been set (by $this->page($page);)
78 $pages = $this->pages
;
79 self
::set_pointer($pages);
80 if(!next($pages)) return false;
83 public function has_previous() {
84 // if the page has been set and it's above 1, then there has to be a previous page
85 if(!empty($this->page
)) {
86 if(($this->page
- 1) > 0) return true;
89 // skips all this extra complicated crap only if $this->page has been set (by $this->page($page);)
90 $pages = $this->pages
;
91 self
::set_pointer($pages);
92 if(!prev($pages)) return false;
95 private function set_pointer(&$pages) {
96 foreach($pages as $page) {
97 $res = array_diff(current($this->pages
), $page);
98 if(empty($res)) break;
103 public function __get($name) {
104 if($name == 'page') return $this->current();
105 if($name == 'next_page') return $this->page +
1;
106 if($name == 'previous_page') return $this->page
- 1;
107 if($name == 'count' ||
$name == 'page_count' ||
$name == 'sizeof') return count($this->collection
);
108 // if($name == '') return $x; //
111 public function __set($name, $value) {
116 class PagerException
extends StdException
{}