właśnie na własne potrzeby napisałem prościutką klasę pagera. Nie posiada metody generującej kod HTML - ten element wykonywany jest już w samym widoku. Klasa lekka, a co za tym idzie szybka.
Do konkstruktora przekazujemy aktualnie wyświetlaną stronę oraz liczbę wszystkich stron.
// EDIT:
dodałem statyczną metodę (calculateTotal()) obliczającą liczbę stron potrzebnych do paginacji
<?php class Pager { protected $_current = 0; protected $_total = 0; protected $_first = false; protected $_previous = false; protected $_next = false; protected $_last = false; public function __construct($current, $total) { $this->_current = (int)$current; $this->_total = (int)$total; // check if $current is >= 1 if ($this->_current < 1) { $this->_current = 1; } // ...or is not out of the $total range else if ($this->_current > $this->_total) { $this->_current = $this->_total; } // set the first, previous... if ($this->_current > 1) { $this->_first = $this->_previous = true; } // ...and next, last if ($this->_current < $this->_total) { $this->_next = $this->_last = true; } } } public function getCurrent() { return $this->_current; } public function getTotal() { return $this->_total; } public function getFirst() { return $this->_first; } public function getPrevious() { return $this->_previous; } public function getNext() { return $this->_next; } public function getLast() { return $this->_last; } } ?>
oraz przykład zastosowania.
W kontrolerze:
<?php // jawne okreslenie liczby stron // obliczenie liczby stron potrzebnych do paginacji ?>
W widoku:
<ul> <li> <?php if ($p->getFirst() === true): ?> <a href="./pager.php?page=1">«</a> <?php else: ?> « <?php endif; ?> </li> <li> <?php if ($p->getPrevious() === true): ?> <?php else: ?> ‹ <?php endif; ?> </li> <?php for($i=1; $i<=$p->getTotal(); $i++): ?> <li> <?php if ($i != $p->getCurrent()): ?> <?php else: ?> <?php endif; ?> </li> <?php endfor; ?> <li> <?php if ($p->getNext() === true): ?> <?php else: ?> » <?php endif; ?> </li> <li> <?php if ($p->getLast() === true): ?> <?php else: ?> › <?php endif; ?> </li> </ul>