Last active
May 31, 2017 22:51
-
-
Save absent1706/4e67bb0f274e24ae8ef1a5c3989bc80b to your computer and use it in GitHub Desktop.
PHP pagination class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Pagination | |
{ | |
public $page; | |
public $totalCount; | |
public $perPage; | |
public $hasNext; | |
public $hasPrev; | |
public $pageCount; | |
public $pages = []; | |
function __construct($page, $perPage, $totalCount) | |
{ | |
$this->page = $page; | |
$this->totalCount = $totalCount; | |
$this->perPage = $perPage; | |
$this->pageCount = (int) ceil($totalCount / $perPage); | |
$this->pages = $this->_pages(); | |
$this->hasNext = $page < $this->pageCount; | |
$this->hasPrev = $page > 1; | |
} | |
protected function _pages($left_edge=2, $left_current=2, $right_current=2, $right_edge=2) | |
{ | |
$pages = []; | |
$previouslyWasNull = false; | |
foreach (range(1, $this->pageCount) as $num) { | |
$includeThisPage = ($num < $left_edge + 1) || | |
(($num > $this->page - $left_current - 1) && ($num < $this->page + $right_current + 1)) || | |
($num > $this->pageCount - $right_edge); | |
if ($includeThisPage) { | |
$pages[] = $num; | |
$previouslyWasNull = false; | |
} | |
elseif ($pages && !$previouslyWasNull) { | |
$pages[] = null; | |
$previouslyWasNull = true; | |
} | |
} | |
return $pages; | |
} | |
} | |
$pagination = new Pagination(2, 10, 1000); | |
var_dump($pagination); echo "\n"; | |
$pagination = new Pagination(50, 10, 1000); | |
var_dump($pagination); echo "\n"; | |
$pagination = new Pagination(98, 10, 1000); | |
var_dump($pagination); echo "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment