16、Hyperf 3 快速使用 - 使用分页器对数据进行分页

作者: 温新

分类: 【Hyperf 3 基础系列】

阅读: 475

时间: 2023-04-25 12:34:25

hi,我是温新,一名 PHPer

Hypref 版本:Hyperf 3.0

学习目标:掌握对数据分页操作

假如有 100 条数据,我们要对这些数据进行分页,Hyperf 实现数据分页,就要引入相对应的扩展包。

安装扩展包

composer require hyperf/paginator

数据分页的基础使用

通过实例化 Hyperf\Paginator\Paginator 类对数据进行分页处理,

该类的构造函数为 __construct($items, int $perPage, ?int $currentPage = null, array $options = [])

构造函数的参数以 数组Hyperf\Utils\Colletion 集合类的形式传递数据到 $items 参数,并设置每页数据量 $perPage 和当前页数 $currentPage$options 参数则可以通过 Key-Value 的形式定义分页器实例内的所有属性。

通过模型类使用

// App\Controller\Test\UserController.php

#[GetMapping('/users/index')]
public function index()
{
    return User::query()->paginate(2);
}

通过模型类使用分页和 Laravel 没有多大区分。下面看看 Hyperf 中分页包的使用。

通过 Hyperf\Paginator\Paginator 使用分页

// App\Controller\Test\UserController.php

use Hyperf\Paginator\Paginator;

#[GetMapping('/users/index')]
public function index(RequestInterface $request)
{
    $currentPage = (int)$request->input('page', 1);
    $perPage     = (int)$request->input('per_page', 2);

    // 这是一个坑哈,取出所有数据后再对其进行分页
    $collections = User::query()->get();
    $users       = array_values($collections->forPage($currentPage, $perPage)->toArray());

    return new Paginator($users, $perPage, $currentPage);
}

分页器相关方法

#[GetMapping('/users/index')]
public function index(RequestInterface $request)
{
    $currentPage = (int)$request->input('page', 1);
    $perPage     = (int)$request->input('per_page', 2);

    // 这是一个坑哈,取出所有数据后再对其进行分页
    $collections = User::query()->get();
    $users       = array_values($collections->forPage($currentPage, $perPage)->toArray());

    $paginator = new Paginator($users, $perPage, $currentPage);

    // 当前页数
    echo $paginator->currentPage() . PHP_EOL;
    // 每页相间条数
    echo $paginator->count() . PHP_EOL;
    // 获取当前页的第一条数据的编号
    echo $paginator->firstItem() . PHP_EOL;
    // 获取当前页的最后一条数据的编号
    echo $paginator->lastItem() . PHP_EOL;
    // 下一页的 URL
    echo $paginator->nextPageUrl() . PHP_EOL;
    // 上一页的 URL
    echo $paginator->previousPageUrl() . PHP_EOL;
    // 获取指定 $page 页数的 URL
    echo $paginator->url($currentPage) . PHP_EOL;

    return $paginator;
}

Hyperf\Paginator\Paginator 没有这个方法,需要使用 Hyperf\Paginator\LengthAwarePaginator

请登录后再评论