返回了很多無用信息,我們也不需要這樣的結(jié)構(gòu)。
{
"current_page": 1,
"data": [
{
"id": 1,
"openid": "abc",
"nickname": "Lucy",
"avatar": "http://avatar.pinxixi.com/0.jpg",
"status": 1,
"last_login_time": 1656553894,
"created": 1656553894,
"updated": 0,
"deleted": 0
}
],
"first_page_url": "/?page=1",
"from": 1,
"last_page": 1,
"last_page_url": "/?page=1",
"links": [
{
"url": null,
"label": "Previous",
"active": false
},
{
"url": "/?page=1",
"label": "1",
"active": true
},
{
"url": null,
"label": "Next",
"active": false
}
],
"next_page_url": null,
"path": "/",
"per_page": 10,
"prev_page_url": null,
"to": 3,
"total": 3
}
我們接口一般這樣返回信息:
{
"code": 0,
"msg": "ok",
"data": {
"users": [
{
"id": 1,
"openid": "abc",
"nickname": "Lucy",
"avatar": "http://avatar.pinxixi.com/0.jpg",
"status": 1,
"last_login_time": 1656553894,
"created": 1656553894,
"updated": 0,
"deleted": 0
}
],
"page": {
"limit": 20,
"p": 1,
"total": 2,
"total_page": 1
}
}
}
我們現(xiàn)在用的框架就很簡單:
$p = Request::getInt('p', 1);
$page = ['limit' => 20, 'p' => $p];
$users = User::where($where)
->fields('id, nickname, avatar, status, last_login_time, created, updated')
->order('last_login_time DESC')
->page($page)
->select();
return App::result(0, 'ok', [
'users' => $users,
'page' => $page
]);
提供一個 bootstrap 解決,注冊到 config/bootstrap.php 中
<?php
namespace app\bootstrap;
use Illuminate\Container\Container;
use Illuminate\Pagination\LengthAwarePaginator;
use Webman\Bootstrap;
class Paginator implements Bootstrap
{
public static function start($worker)
{
// 修改分頁返回的結(jié)構(gòu)
Container::getInstance()->bind(LengthAwarePaginator::class, function (Container $app, array $options) {
return new class($options['items'], $options['total'], $options['perPage'], $options['currentPage'], $options['options']) extends LengthAwarePaginator {
/**
* @inheritDoc
*/
public function toArray()
{
return [
'items' => $this->items->toArray(),
'total' => $this->total(),
];
}
};
});
}
}
<?php
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
* Here is your custom functions.
*/
function listPage(LengthAwarePaginator $paginator)
{
return [
$paginator->items(),
[
'limit' => $paginator->perPage(),
'p' => $paginator->currentPage(),
'total' => $paginator->total(),
'total_page' => $paginator->lastPage()
]
];
}
<?php
namespace App\controller;
use support\Db;
use support\Request;
class User
{
public function list(Request $request)
{
$p = $request->getInt('p', 1);
$per_page = 10;
$paginator = Db::table('user')->where('id', '>', 1)->paginate($per_page, '*', 'page', $p);
list($users, $page) = listPage($paginator);
return jsons(0, 'ok', [
'users' => $users,
'page' => $page
]);
}
}