vic4884
1/5/2020 - 10:15 AM

Pagination class

<?php

class Pagination
{
    public $current_page; // текущая страница
    public $table; // название таблицы из которой нужно брать строки
    public $params; // дополнительные параметры для запроса в базу
    public $count_rows; // количество записей в базе
    public $limit; // максимаьное количество получаемых записей
    public $offset; // с какой строки получать данные из базы
    public $total_pages; // всего страниц для пагинации


    public function __construct($table, $params = '', $limit)
    {
        $this->current_page = $this->getCurrentPage();
        $this->table = $table;
        $this->params = $params;
        $this->count_rows = $this->getCountRows ();
        $this->limit = $limit;
        $this->offset = $this->getOffset();
        $this->total_pages = $this->getTotalPages();
    }

    public function getCurrentPage()
    {
        if ( isset($_GET['page']) && $_GET['page'] > 0 ) { // номер страницы
            $current_page = intval($_GET['page']); // -1 /-> 1 , -3 /-> 3
        } else {
            $current_page = 1;
        }
        return $current_page;
    }

    public function getCountRows() // количестко записей в базе
    {
        global $app; // подключение к бд
        $table = $this->table;
        $params = $this->params;
        $query = "select count(*) as count from {$table} {$params}";
        return $app['database']->getRows($query)[0]['count'];
    }

    public function getOffset()
    {
        $current_page = $this->current_page;
        $limit = $this->limit;
        return ($current_page - 1) * $limit;
    }

    public function getTotalPages()
    {
        $count_rows = $this->count_rows;
        $limit = $this->limit;
        return intval(($count_rows - 1) / $limit) + 1;
    }

    public function __toString()
    {
        $out = "<div class='pagination'>";
        $current_page = $this->current_page;
        $total_pages = $this->total_pages;

        if ($current_page > $total_pages) {
            $out = "<p>Запрашиваемой страницы #$current_page не существует</p>
                    <br>
                   <a href='$path'>Вернуться на главную</a>";
        } else {
            for ($i = 1; $i <= $total_pages; $i++) {
                $current_page == $i ? $attr = "class='active'" : $attr = "href='?page=$i'";
                $out .=  "<a $attr>$i</a>";
            }
        }
        $out .= "</div>";
        return $out;
    }
}