tp程序自带了分页的功能,用起来很是方便,特别是默认情况下直接连样式都写好了。非常的省心。但这只是对于数据库操作而言。如果我们想要对请求的接口数据进行分页,那么该如何使用paginate方法呢?
修改说明
增加了注释,参考附录代码。
此代码的使用场景:在php中curl请求带分页的接口中使用
解决html显示异常,模板中使用raw方法
知其然
我们首先来查看tp数据的分页流程是怎么样的。先写一个数据库分页的代码
$page = Db::name("null")
->paginate();
$page->render();
使用ctrl+鼠标左键,进入paginate方法中。
...
/** @var Paginator $class */
$class = false !== strpos($config['type'], '\\') ? $config['type'] : '\\think\\paginator\\driver\\' . ucwords($config['type']);
$page = isset($config['page']) ? (int) $config['page'] : call_user_func([
$class,
'getCurrentPage',
], $config['var_page']);
$page = $page < 1 ? 1 : $page;
$config['path'] = isset($config['path']) ? $config['path'] : call_user_func([$class, 'getCurrentPath']);
if (!isset($total) && !$simple) {
$options = $this->getOptions();
unset($this->options['order'], $this->options['limit'], $this->options['page'], $this->options['field']);
$bind = $this->bind;
$total = $this->count();
$results = $this->options($options)->bind($bind)->page($page, $listRows)->select();
} elseif ($simple) {
$results = $this->limit(($page - 1) * $listRows, $listRows + 1)->select();
$total = null;
} else {
$results = $this->page($page, $listRows)->select();
}
return $class::make($results, $listRows, $page, $total, $simple, $config);
这里只粘贴了重要代码。我们看最后一句,$class 的实例化在上面代码块的第一行,这个类就是分页驱动类。调用了make方法。我们再跟踪进make方法进行查看
public static function make($item