PHPackages                             timefrontiers/php-pagination - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. timefrontiers/php-pagination

ActiveLibrary[Database &amp; ORM](/categories/database)

timefrontiers/php-pagination
============================

PHP pagination trait for database objects and collections

v1.0.0(1mo ago)020↓100%4MITPHPPHP &gt;=8.1

Since Apr 16Pushed 1mo agoCompare

[ Source](https://github.com/timefrontiers/php-pagination)[ Packagist](https://packagist.org/packages/timefrontiers/php-pagination)[ Docs](https://github.com/timefrontiers/php-pagination)[ RSS](/packages/timefrontiers-php-pagination/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (4)

TimeFrontiers PHP Pagination
============================

[](#timefrontiers-php-pagination)

Lightweight PHP pagination trait for database objects and collections.

Installation
------------

[](#installation)

```
composer require timefrontiers/php-pagination
```

Quick Start
-----------

[](#quick-start)

```
use TimeFrontiers\Helper\Pagination;

class UserRepository {
  use Pagination;

  public function getUsers():array {
    // Set pagination from request (?page=2&per_page=25)
    $this->fromRequest();

    // Get total count
    $this->setTotalCount($this->countAll());

    // Query with pagination
    $sql = "SELECT * FROM users {$this->limitClause()}";

    return $this->query($sql);
  }
}

$repo = new UserRepository();
$users = $repo->getUsers();

// Display info
echo "Page {$repo->currentPage()} of {$repo->totalPages()}";
echo "Showing {$repo->itemStart()}-{$repo->itemEnd()} of {$repo->totalCount()}";
```

Usage with DatabaseObject
-------------------------

[](#usage-with-databaseobject)

```
use TimeFrontiers\Helper\DatabaseObject;
use TimeFrontiers\Helper\Pagination;

class User {
  use DatabaseObject, Pagination;

  protected static string $_table_name = 'users';
}

// In controller
$user = new User();
$user->fromRequest()->setTotalCount(User::countAll());

$users = User::findBySql(
  "SELECT * FROM users ORDER BY created_at DESC {$user->limitClause()}"
);

// Pass pagination to view
$pagination = $user->paginationToArray();
```

Configuration
-------------

[](#configuration)

### Set Page

[](#set-page)

```
$this->setPage(3);           // Go to page 3
$this->setPerPage(50);       // 50 items per page
$this->setTotalCount(1000);  // 1000 total items
```

### From Request

[](#from-request)

```
// Uses $_GET['page'] and $_GET['per_page']
$this->fromRequest();

// Custom parameter names
$this->fromRequest('p', 'limit', 25);
// Uses $_GET['p'] for page, $_GET['limit'] for per_page, default 25
```

Getters
-------

[](#getters)

```
$this->currentPage();  // int: Current page number
$this->perPage();      // int: Items per page
$this->totalCount();   // int: Total items
$this->totalPages();   // int: Total pages
$this->offset();       // int: SQL OFFSET value
```

Navigation
----------

[](#navigation)

```
$this->previousPage();     // int: Previous page number
$this->nextPage();         // int: Next page number
$this->hasPreviousPage();  // bool: Has previous?
$this->hasNextPage();      // bool: Has next?
$this->isFirstPage();      // bool: On first page?
$this->isLastPage();       // bool: On last page?

```

Item Range
----------

[](#item-range)

```
// Page 2, 20 per page, 95 total items
$this->itemStart();  // 21
$this->itemEnd();    // 40
$this->itemRange();  // [21, 40]

// "Showing 21-40 of 95 results"
echo "Showing {$this->itemStart()}-{$this->itemEnd()} of {$this->totalCount()} results";
```

State Checks
------------

[](#state-checks)

```
$this->isEmpty();       // bool: No results?
$this->isNotEmpty();    // bool: Has results?
$this->hasPages();      // bool: More than 1 page?
$this->isValidPage(5);  // bool: Is page 5 valid?

```

SQL Helpers
-----------

[](#sql-helpers)

```
// LIMIT clause
$sql = "SELECT * FROM users {$this->limitClause()}";
// "SELECT * FROM users LIMIT 20 OFFSET 40"

// As array
$limit = $this->limitOffset();
// ['limit' => 20, 'offset' => 40]
```

Page Range for UI
-----------------

[](#page-range-for-ui)

```
// Generate page numbers for pagination UI
// Current page: 5, Total: 20
$pages = $this->pageRange(2);
// [1, null, 3, 4, 5, 6, 7, null, 20]
// null = ellipsis (...)

// Render pagination
foreach ($this->pageRange(2) as $page) {
  if ($page === null) {
    echo '...';
  } else {
    $active = $page === $this->currentPage() ? 'active' : '';
    echo "{$page}";
  }
}

// Get all pages (no ellipsis)
$this->pages();  // [1, 2, 3, 4, 5, ...]
```

URL Helpers
-----------

[](#url-helpers)

```
// Build URL for specific page
$this->pageUrl(3);  // "/users?page=3&search=john"

// Previous/Next URLs
$this->previousPageUrl();  // "/users?page=1" or null
$this->nextPageUrl();      // "/users?page=3" or null

// Custom base URL
$this->pageUrl(5, '/api/users', 'p');  // "/api/users?p=5"
```

API Response
------------

[](#api-response)

```
// Basic metadata
$meta = $this->paginationToArray();
/*
[
  'current_page'  => 2,
  'per_page'      => 20,
  'total'         => 95,
  'total_pages'   => 5,
  'from'          => 21,
  'to'            => 40,
  'has_more'      => true,
  'is_first_page' => false,
  'is_last_page'  => false,
]
*/

// With links
$meta = $this->paginationMeta('/api/users');
/*
[
  'current_page' => 2,
  ...
  'links' => [
    'first' => '/api/users?page=1',
    'last'  => '/api/users?page=5',
    'prev'  => '/api/users?page=1',
    'next'  => '/api/users?page=3',
  ]
]
*/

// API response
return [
  'data' => $users,
  'meta' => $this->paginationMeta(),
];
```

Complete Example
----------------

[](#complete-example)

### Repository Pattern

[](#repository-pattern)

```
class ArticleRepository {
  use Pagination;

  private PDO $db;

  public function __construct(PDO $db) {
    $this->db = $db;
  }

  public function getPaginated(array $filters = []):array {
    // Configure from request
    $this->fromRequest();

    // Build query
    $where = $this->buildWhere($filters);

    // Get total count
    $countSql = "SELECT COUNT(*) FROM articles {$where}";
    $total = $this->db->query($countSql)->fetchColumn();
    $this->setTotalCount((int)$total);

    // Get paginated results
    $sql = "SELECT * FROM articles {$where}
            ORDER BY created_at DESC
            {$this->limitClause()}";

    $articles = $this->db->query($sql)->fetchAll();

    return [
      'data' => $articles,
      'meta' => $this->paginationToArray(),
    ];
  }
}
```

### Controller

[](#controller)

```
$repo = new ArticleRepository($pdo);
$result = $repo->getPaginated(['status' => 'published']);

// JSON API
header('Content-Type: application/json');
echo json_encode($result);
```

### Blade-style View

[](#blade-style-view)

```

  Showing -
  of  results
