hizpark/paginator

Flexible pagination utility for PHP applications

v1.0.0 2025-09-03 17:07 UTC

This package is auto-updated.

Last update: 2025-09-03 17:18:50 UTC


README

PHP pagination made easy

License Latest Version PHP Version Static Analysis Tests codecov CI

Flexible pagination for PHP applications.

✨ 特性

  • Calculate total pages, current page, previous and next pages.
  • Generate page numbers for navigation with ellipsis support.
  • Provides query limits and offsets for database queries.
  • Handles edge cases like first page, last page, and single-page scenarios.
  • Fully typed and compatible with PHP 8+.

📦 安装

composer require hizpark/paginator

📂 目录结构

src
└── Paginator.php

🚀 用法示例

示例 1:基础分页导航

use Hizpark\Paginator\Paginator;

// 假设总共有 120 条记录,每页 10 条,当前在第 5 页
$paginator = new Paginator(totalRows: 120, pageSize: 10, pageNumber: 5);

// 当前页码
echo $paginator->currentPage(); // 5

// 总页数
echo $paginator->totalPages(); // 12

// 上一页 / 下一页
echo $paginator->prevNumber(); // 4
echo $paginator->nextNumber(); // 6

// 页码数组(用于显示分页导航)
print_r($paginator->pageNumbers());
// 输出示例: [1, '…', 4, 5, 6, '…', 12]

示例 2:结合数据库查询分页

use Hizpark\Paginator\Paginator;
use PDO;

// 假设数据库有 120 条记录,每页 10 条,当前第 3 页
$totalRows  = 120;
$pageSize   = 10;
$pageNumber = 3;

$paginator = new Paginator($totalRows, $pageSize, $pageNumber);

// PDO 查询示例
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'pass');
$stmt = $pdo->prepare('SELECT * FROM posts LIMIT :limit OFFSET :offset');
$stmt->bindValue(':limit', $paginator->limitForQuery(), PDO::PARAM_INT);
$stmt->bindValue(':offset', $paginator->offsetForQuery(), PDO::PARAM_INT);
$stmt->execute();

$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 打印结果
print_r($rows);

🔍 静态分析

使用 PHPStan 工具进行静态分析,确保代码的质量和一致性:

composer stan

🎯 代码风格

使用 PHP-CS-Fixer 工具检查代码风格:

composer cs:chk

使用 PHP-CS-Fixer 工具自动修复代码风格问题:

composer cs:fix

✅ 单元测试

执行 PHPUnit 单元测试:

composer test

执行 PHPUnit 单元测试并生成代码覆盖率报告:

composer test:coverage

🤝 贡献指南

欢迎 Issue 与 PR,建议遵循以下流程:

  1. Fork 仓库
  2. 创建新分支进行开发
  3. 提交 PR 前请确保测试通过、风格一致
  4. 提交详细描述

📜 License

MIT License. See the LICENSE file for details.