123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199 |
- <?php
- namespace App\Models;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Log;
- use Illuminate\Support\Facades\Cache;
- class Pages
- {
- public $model; // Eloquent 模型
- public $request; // 请求对象
- public $beforeClosure; // 执行前的闭包
- public $afterClosure; // 执行后的闭包
- protected $useCache = false; // 缓存开关
- protected $cacheTTL = 3600; // 缓存过期时间,单位为秒,默认 1 小时
- /**
- * 构造函数接收模型和请求对象
- *
- * @param Request $request 请求对象
- * @param Object $model Eloquent 模型
- */
- public function __construct(Request $request, $model)
- {
- $this->request = $request;
- $this->model = $model;
- }
- /**
- * 设置是否使用缓存
- *
- * @param boolean $enabled 缓存开关
- * @param integer $ttl 缓存过期时间,单位为秒
- * @return void
- */
- public function withCache($enabled = true, $ttl = 3600)
- {
- $this->useCache = $enabled;
- $this->cacheTTL = $ttl; // 设置缓存过期时间
- return $this;
- }
- // 获取缓存的键
- private function getCacheKey()
- {
- // 获取分页参数,默认值为 1 和 10
- $page = $this->request->input('page', 1);
- $pageSize = $this->request->input('page_size', 10);
- // 获取请求路径
- $url = $this->request->url();
- // 将 URL 和分页参数拼接成缓存键
- return 'page_' . md5($url . '?' . http_build_query(['page' => $page, 'page_size' => $pageSize]));
- }
- /**
- * 关联查询
- *
- * @param array $relations 关联的模型:如 ['user', 'category']
- * @return void
- */
- public function withRelations(array $relations)
- {
- $this->model = $this->model->with($relations);
- return $this;
- }
- /**
- * 设置执行前操作的闭包
- *
- * @param callable $closure 闭包函数,$query 为模型对象
- * @return void
- */
- public function before(callable $closure)
- {
- $this->beforeClosure = function ($query) use ($closure) {
- // 添加全局过滤逻辑,比如按条件自动加 where
- // $query->where('status', 1);
- return call_user_func($closure, $query);
- };
- }
- /**
- * 设置执行后操作的闭包
- *
- * @param callable $closure 闭包函数,$data 为查询结果
- * @return void
- */
- public function after(callable $closure)
- {
- $this->afterClosure = function ($data) use ($closure) {
- // 添加全局处理逻辑,比如隐藏某些字段
- // $data->makeHidden('sale_price');
- return call_user_func($closure, $data);
- };
- }
- // 执行前操作
- private function beforeExecution()
- {
- if (is_callable($this->beforeClosure)) {
- $this->model = call_user_func($this->beforeClosure, $this->model);
- }
- }
- // 执行后操作
- private function afterExecution($data)
- {
- if (is_callable($this->afterClosure)) {
- return call_user_func($this->afterClosure, $data);
- }
- return $data;
- }
- // 获取分页数据
- public function paginate()
- {
- try {
- // 使用注入的 Request 对象获取分页参数
- $perPage = $this->request->input('page_size', 10); // 获取每页显示的数量,默认值为10
- $sortBy = $this->request->input('sort_by', 'id'); // 默认按 id 排序
- $sortOrder = $this->request->input('sort_order', 'desc'); // 默认升序排序
- $page_not = $this->request->input('page_not', false); // 是否不使用分页
- // 执行前操作
- $this->beforeExecution();
- // 不使用分页
- if ($page_not) {
- $dataList = $this->afterExecution($this->model->get());
- return response()->json([
- 'code' => 1,
- 'msg' => "请求成功",
- // 当前页的数据,实际的分页数据,是当前页展示的内容
- 'data' => $dataList,
- ], 200);
- }
- // 排序功能
- $tableName = $this->model->getModel()->getTable();
- $this->model->orderBy($tableName . "." . $sortBy, $sortOrder);
- // 如果开启了缓存,首先检查缓存是否存在
- if ($this->useCache && Cache::store('redis')->has($this->getCacheKey())) {
- // 从缓存中获取分页数据
- // Log::info('从缓存中获取分页数据'.$this->getCacheKey());
- $paginator = Cache::store('redis')->get($this->getCacheKey());
- } else {
- // 执行分页查询
- $paginator = $this->model->paginate($perPage);
- // $paginator = $this->model->paginate($perPage,['*'] ,'page_now'); // 自定义分页字段
- // 如果开启了缓存,则缓存查询结果
- if ($this->useCache) {
- Cache::store('redis')->put($this->getCacheKey(), $paginator, $this->cacheTTL);
- }
- }
- // 执行后操作
- $this->afterExecution($paginator);
- return response()->json([
- 'code' => 1,
- 'msg' => "请求成功",
- // 当前页的数据,实际的分页数据,是当前页展示的内容
- 'data' => $paginator->items(),
- 'page_info' => [
- // 当前页码,指示用户当前所在的页数
- 'page_now' => $paginator->currentPage(),
- // 总页数,表示所有数据分成多少页
- 'page_count' => $paginator->lastPage(),
- // 总记录数,表示所有数据的总数
- 'total_count' => $paginator->total(),
- // 每页的记录数,表示每一页显示的数据量
- 'page_size' => $paginator->perPage(),
- // 当前页的第一条记录的序号,指示该页显示的第一项数据是第几条记录
- // 'from' => $paginator->firstItem(),
- // 当前页的最后一条记录的序号,指示该页显示的最后一项数据是第几条记录
- // 'to' => $paginator->lastItem(),
- ]
- ], 200);
- } catch (\Exception $e) {
- Log::error('分页查询失败: ' . $e->getMessage());
- return response()->json([
- 'code' => 0,
- 'msg' => "请求失败",
- ], 400);
- }
- }
- }
|