以下是一个使用 ThinkPHP6 构建的复杂分页模块的示例代码:
控制器代码:
<?php
namespace app\controller;
use app\model\User;
use think\Controller;
use think\facade\View;
class UserController extends Controller
{
public function index()
{
$userModel = new User();
// 每页显示的记录数
$pageSize = 10;
// 获取用户总数
$totalCount = $userModel->count();
// 计算总页数
$totalPage = ceil($totalCount / $pageSize);
// 当前页码
$page = input('page', 1, 'intval');
// 计算偏移量
$offset = ($page - 1) * $pageSize;
// 获取用户列表
$userList = $userModel->limit($offset, $pageSize)->select();
// 渲染模板并输出
return View::fetch('user/index', [
'userList' => $userList,
'totalCount' => $totalCount,
'totalPage' => $totalPage,
'pageSize' => $pageSize,
'currentPage' => $page,
]);
}
}
模板代码:
<!-- user/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户列表</title>
</head>
<body>
<table>
<thead>
<tr>
<th>ID</th>
<th>用户名</th>
<th>邮箱</th>
</tr>
</thead>
<tbody>
<?php foreach ($userList as $user): ?>
<tr>
<td><?php echo $user->id; ?></td>
<td><?php echo $user->username; ?></td>
<td><?php echo $user->email; ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="pagination">
<?php if ($currentPage > 1): ?>
<a href="<?php echo url('user/index', ['page' => $currentPage - 1]); ?>">上一页</a>
<?php endif; ?>
<?php for ($i = 1; $i <= $totalPage; $i++): ?>
<?php if ($i == $currentPage): ?>
<span class="current"><?php echo $i; ?></span>
<?php else: ?>
<a href="<?php echo url('user/index', ['page' => $i]); ?>"><?php echo $i; ?></a>
<?php endif; ?>
<?php endfor; ?>
<?php if ($currentPage < $totalPage): ?>
<a href="<?php echo url('user/index', ['page' => $currentPage + 1]); ?>">下一页</a>
<?php endif; ?>
</div>
</body>
</html>
此示例代码演示了如何使用 ThinkPHP6 实现复杂的分页功能,包括获取总记录数、计算总页数、计算偏移量、查询数据、以及渲染模板并输出分页导航。