kosinix/paginator

一个通用的PHP类,用于将大量数据分割成小块以便在Web应用中使用

3.0.0 2016-11-04 07:57 UTC

This package is not auto-updated.

Last update: 2024-09-14 17:32:02 UTC


README

一个通用的PHP类,用于将大量数据分割成小块以便在Web应用中使用。

要求

  • PHP >= 5.3.3

安装

手册

  • 从Github仓库下载zip文件。
  • 解压zip文件,并将文件包含到您的项目中。
  • 在/src/中包含该类
require_once '/path/to/src/Kosinix/Paginator.php'; // Change this to the correct path

Composer

在项目目录中,打开命令行并输入

composer require kosinix/paginator:dev-master --prefer-dist

包含在vendor/中找到的autoload.php

require_once '/path/to/vendor/autoload.php'; // Change this to the correct path

使用方法

包含类并传递所需的参数

require_once 'src/Kosinix/Paginator.php';

$total = 23; // This will come from your app. Eg. do an SQL count: 'SELECT COUNT(*) AS `total` FROM user'
$current_page = 2; // This will come from your app. Eg. $current_page = $_GET['page'];
$per_page = 10; // This will also come from your app. 

$paginator = new \Kosinix\Paginator($total, $current_page, $per_page);

$sql = sprintf('SELECT * FROM users LIMIT %d,%d', $paginator->getStartIndex(), $paginator->getPerPage());

// Run sql query here

构造函数接受以下参数

  • total - 记录总数。
  • current_page - 要显示的当前页面。默认为1。
  • per_page - 每页的记录数。默认为10。

以下图像最好地解释了这些术语

alt tag

Silex Service Provider

您还可以为paginator创建一个服务提供者以用于Silex

// PaginatorServiceProvider.php

use Silex\Application;
use Silex\ServiceProviderInterface;
use Kosinix\Paginator;

class PaginatorServiceProvider implements ServiceProviderInterface {

    public function register(Application $app) {
        $app['paginator.per_page'] = isset($app['paginator.per_page']) ? (int)$app['paginator.per_page'] : 10;
        $app['paginator'] = $app->protect(
            function ($total, $page, $per_page=null) use ($app) {
                if(null === $per_page){
                    $per_page = $app['paginator.per_page'];
                }
                return new Paginator($total, $page, $per_page);
            }
        );
    }

    public function boot(Application $app) {

    }
}

然后在您的应用程序中

// Paginator
$app->register(new PaginatorServiceProvider());

在您的控制器中

$sql = 'SELECT COUNT(*) AS `total` FROM product';
$count = $app['db']->fetchAssoc($sql);
$count = (int) $count['total'];

/** @var \Kosinix\Paginator $paginator */
$paginator =  $app['paginator']($count, $page); // $page would come from your web app

测试

  • 转到项目文件夹并在命令行中运行phpunit。
  • 您需要全局安装phpunit。

许可

  • MIT