Witam,
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;
}
}
static public function calculateTotal
($count, $perPage) { return ceil($count/$perPage); }
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
$view->p = new Pager
((isset($_GET['page']) ?
$_GET['page'] : 1
), 10
); // obliczenie liczby stron potrzebnych do paginacji
$view->p = new Pager
((isset($_GET['page']) ?
$_GET['page'] : 1
), Pager
::calculateTotal(101
, 10
)); ?>
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): ?>
<a href="./pager.php?page=
<?php echo $p->getCurrent()-1; ?>">‹</a>
<?php else: ?>
‹
<?php endif; ?>
</li>
<?php for($i=1; $i<=$p->getTotal(); $i++): ?>
<li>
<?php if ($i != $p->getCurrent()): ?>
<a href="./pager.php?page=
<?php echo $i; ?>">
<?php echo $i; ?></a>
<?php else: ?>
<?php endif; ?>
</li>
<?php endfor; ?>
<li>
<?php if ($p->getNext() === true): ?>
<a href="./pager.php?page=
<?php echo $p->getCurrent()+1; ?>">»</a>
<?php else: ?>
»
<?php endif; ?>
</li>
<li>
<?php if ($p->getLast() === true): ?>
<a href="./pager.php?page=
<?php echo $p->getTotal(); ?>">›</a>
<?php else: ?>
›
<?php endif; ?>
</li>
</ul>
Ten post edytował phpion.com 30.12.2007, 10:33:54