Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Class Pagination
- *
- * @author Luciano Charles de Souza
- * E-mail: souzacomprog@gmail.com
- * Github: https://github.com/LucianoCharlesdeSouza
- * YouTube: https://www.youtube.com/channel/UC2bpyhuQp3hWLb8rwb269ew?view_as=subscriber
- */
- class Pagination
- {
- private $pdo;
- private $indexPage = 0;
- private $links = '';
- private $maxPage = 2;
- private $maxLinks = 2;
- private $places = [];
- private $page = 'page';
- private $query = '';
- private $queryCount = null;
- public function __construct(\PDO $pdo)
- {
- $this->pdo = $pdo;
- }
- /**
- * Método que recebe o valor máximo de registros por página
- * @param $max int
- * @throws Exception
- */
- public function maxPerPage($max)
- {
- if (!is_int($max) || !is_numeric($max)) {
- throw new Exception("Passe um valor inteiro para o máximo de registro por páginas!");
- }
- $this->maxPage = (int) $max;
- }
- /**
- * Método que recebe o nome do page
- * @param $namePage string
- * @throws Exception
- */
- public function page($namePage)
- {
- if (!is_string($namePage)) {
- throw new Exception("O nome do paginador deve ser tipo string!");
- }
- $this->page = (string) $namePage;
- }
- /**
- * Método que recebe o valor máximo de links visiveis a esquerda e direita
- * @param $maxlinks int
- * @throws Exception
- */
- public function maxLinks($maxlinks)
- {
- if (!is_int($maxlinks) || !is_numeric($maxlinks)) {
- throw new Exception("Passe um valor para o máximo de links!");
- }
- $this->maxLinks = (int) $maxlinks;
- }
- /**
- * Método que retorna
- * os itens para a paginação
- * @return array
- */
- public function paginate($where = null)
- {
- $Query = "SELECT DISTINCT * FROM {$this->table} {$where}";
- $this->getIndexPage();
- $this->query .= $Query . " LIMIT " . $this->indexPage . "," . $this->maxPage;
- return $this->fullSql($this->query, $this->places);
- }
- /**
- * Método que recebe uma string SQL para retornar
- * os itens para a paginação
- * @param $Query string
- * @return array
- */
- public function createPagination($Query)
- {
- $this->getIndexPage();
- $this->query .= $Query . " LIMIT " . $this->indexPage . "," . $this->maxPage;
- return $this->fullSql($this->query, $this->places);
- }
- /**
- * Método que recebe um array para usar como substitutos no Bind
- * @param array $placesValues
- */
- public function bindValues(array $placesValues)
- {
- $this->places = $placesValues;
- }
- /**
- * Método que gera os links de paginação
- * @return string
- */
- public function createLinks()
- {
- $this->pagingNumberExceeded();
- if ($this->totalRecords() > $this->maxPage) {
- $this->firstLink();
- $this->previousLink();
- $this->currentLink();
- $this->nextLink();
- $this->lastLink();
- }
- return $this->links;
- }
- /**
- * Método que recebe o valor atual da paginação
- * @return int|string
- */
- private function getPager()
- {
- $pager = filter_input(INPUT_GET, $this->page);
- return (isset($pager) ? (int) $pager : $pager . 1);
- }
- /**
- * Método que recebe objeto PDO mais o array Places,
- * gerando os Bind's
- * @param $stmt
- * @param null $Fields array
- */
- private function createBind($stmt, $Fields = null)
- {
- if ($Fields != null) {
- foreach ($Fields as $key => $value) {
- $stmt->bindValue(":$key", $value);
- }
- }
- }
- private function debugueParamns($stmt)
- {
- echo '<pre>';
- return var_dump($stmt->debugDumpParams());
- }
- /**
- * Método que recebe uma string SQL,
- * podendo ou não receber também um array para as substituições
- * no Bind
- * @param $Query string
- * @param array|null $Fields
- * @return array
- */
- private function fullSql($Query, array $Fields = null)
- {
- try {
- $sql = strtolower($Query);
- $update = (strpos($sql, "update") !== false) ? true : false;
- $delete = (strpos($sql, "delete") !== false) ? true : false;
- $insert = (strpos($sql, "insert") !== false) ? true : false;
- $stmt = $this->pdo->prepare($Query);
- $this->createBind($stmt, $Fields);
- $stmt->execute();
- if ($update) {
- return true;
- }
- if ($delete) {
- return true;
- }
- if ($insert) {
- return true;
- }
- if ($stmt->rowCount() > 0) {
- return $stmt->fetchAll();
- }
- return false;
- } catch (\PDOException $e) {
- die($e->getMessage());
- }
- }
- /**
- * Método que retorna o número da página
- * @return int
- */
- private function getIndexPage()
- {
- if ((($this->maxPage * $this->getPager()) - $this->maxPage) > 0) {
- return $this->indexPage = (($this->maxPage * $this->getPager()) - $this->maxPage);
- }
- return $this->indexPage = 0;
- }
- /**
- * Método que retorna a quantidade de registros da consulta,
- * que é usada para auxiliar na lágica da paginação
- * @return mixed
- */
- private function totalRecords()
- {
- $sql = str_replace(" LIMIT " . $this->indexPage . "," . $this->maxPage, '', $this->query);
- $total = ($this->fullSql($sql, $this->places)) ? count($this->fullSql($sql, $this->places)) : 0;
- return $total;
- }
- /**
- * Método que retorna o total de páginas que terá a paginação
- * @return float
- */
- private function totalPages()
- {
- return ceil($this->totalRecords() / $this->maxPage);
- }
- /**
- * Método que fará o redirecionamento sempre para a última página,
- * caso o usuário passe uma valor não existente de forma manual na url
- */
- private function pagingNumberExceeded()
- {
- if (($this->getPager() > $this->totalPages() || $this->getPager() < 1) && $this->totalRecords() != 0) {
- header("Location: " . $this->ReturnPageValid($this->page) . "?" . $this->page . "=" . $this->totalPages());
- }
- }
- /**
- * Método que gera o html para o primeiro item da paginação
- */
- private function firstLink()
- {
- $this->links .= "<div class=\"col-sm-12 text-center\"><ul class=\"pagination\">";
- $first = "<li class=\"page-item\"><a class=\"page-link\" href = \"?" . $this->page . "=1\">«</a></li>";
- $this->links .= $first;
- }
- /**
- * Método que gera o html para o item anterior da paginação atual
- */
- private function previousLink()
- {
- for ($i = $this->getPager() - $this->maxLinks; $i <= $this->getPager() - 1; $i++) {
- if ($i >= 1) {
- $this->links .= "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $i . "\">" . $i . "</a></li>";
- }
- }
- }
- /**
- * Método que gera o html para o item atual da paginação
- */
- private function currentLink()
- {
- $this->links .= "<li class=\"page-item active\"><a class=\"page-link\" href='#'>" . $this->getPager() . " <span class=\"sr-only\">(current)</span></a></li>";
- }
- /**
- * Método que gera o html para o próximo item da paginação atual
- */
- private function nextLink()
- {
- for ($i = $this->getPager() + 1; $i <= $this->getPager() + $this->maxLinks; $i++) {
- if ($i <= $this->totalPages()) {
- $this->links .= "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $i . "\">" . $i . "</a></li>";
- }
- }
- }
- /**
- * Método que gera o html para o último item da paginação
- */
- private function lastLink()
- {
- $last = "<li class=\"page-item\"><a class=\"page-link\" href=\"?" . $this->page . "=" . $this->totalPages() . "\">»</a></li></ul></div>";
- $this->links .= $last;
- }
- /**
- * Método que retorna a url com o nome do page, porem sem o valor da paginação
- * @param $namePager
- * @return bool|string
- */
- private function ReturnPageValid($namePager)
- {
- $URL = filter_input(INPUT_SERVER, 'HTTP_HOST');
- $url = "http://" . $URL . filter_input(INPUT_SERVER, 'REQUEST_URI');
- $https = filter_input(INPUT_SERVER, 'HTTPS');
- if (isset($https) && $https == 'on') {
- $url = "https://" . $URL . filter_input(INPUT_SERVER, 'REQUEST_URI');
- }
- return substr($url, 0, strpos($url, "?" . $namePager));
- }
- }
- USO DA CLASSE
- //Objeto PDO para ser injetado no construtor da classe Pagination
- $pdo = ConnPDO::getInstance();
- require('Pagination.php');
- $pagination = new Pagination($pdo);
- try {
- $listagem = $pagination->CreatePagination("SELECT * FROM menu");
- $links = $pagination->CreateLinks();
- } catch (Exception $e) {
- die($e->getMessage());
- }
- /* Aqui em listagem voce pode criar uma tabela em html e extrair os dados nesta tabela */
- echo "<pre>";
- var_dump($listagem);
- echo "<pre>";
- echo $links;
- Se herdares esta classe, poderas colocar um atributo pretected $table = 'nome_da_tabela_no_banco';
- para poder usar o metodo paginate para paginações simples
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement