done-super-app/queryoption 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

done-super-app/queryoption

Composer 安装命令:

composer create-project done-super-app/queryoption

包简介

Package to help with filtering/search/sort in queries

README 文档

README

Query Option package logo
QueryOption

Tests Total Downloads License

This package helps you manipulate HTTP query data as an object instead of passing an array through different layers of your application.

Usage

Inside a controller we tend to extract the params from the request and send them to our service and then to the repository to perform search, sort or filtering.

class ListUsersController as Controller
{
    private UserService $userService;

    public function __construct(UserService $userService) {
        $this->userService = $userService;
    }

    public function __invoke(Request $request) {
        $queryOption = QueryOptionFactory::createFromIlluminateRequest($request);

        $this->userService->paginate($queryOption);
    }
}

From the example above, the QueryOptionFactory helps create the QueryOption object that hold values needed for search, sort and filters. Since in this example we have a Laravel application, we can use a specific factory method to crate directly from Request object.

createFromGlobals() create the QueryOption object from the global $_REQUEST object.
createFromArray(array $attributes) create the QueryOption object from an array passed in param.
createFromIlluminateRequest(Request $request) create the QueryOption object from a Laravel Illuminate request object.
createFromSymfonyRequest(Request $request) create the QueryOption object from a Symfony HTTP foundation request object.

URL Params

Since the QueryOption package parse the URL parameters, we're going to explain the param names below:

q Used for search
search_type (like: default, equal)
page Current page (when working with pagination)
limit Limit query result (when working with pagination)
sort_field Name of the field when sorting (created_at: default)
sort_order Sorting direction. (asc, desc: default)
filters An array of filters (as described below)
field Name of the field to filter by
operator Comparison operator (=: default, !=, >, <, =>, <=, is, is_not, in)
value The value to compare by

Query Option

The QueryOption is the glue that holds all the rest of the components.

$queryOption->getSort();
$queryOption->getFilters();
$queryOption->getSearch();

For most applications, each controller has a set of filters that are allowed in certain context (admin vs normal user). In this case, you can use the allowedFilters() method inside the controller to limit passing filters in the wrong context.

An example would be listing blog posts. The admin can all the posts, while the normal user can only see the published ones.

class AdminPostsController {
    private PostService $postService;

    public function __construct(PostService $postService) {
        $this->postService = $postService;
    }

    public function __invoke(Request $request) {
        $queryOption = QueryOptionFactory::createFromIlluminateRequest($request);

        $posts = $this->postService->paginate($queryOption);

        // return posts
    }
}
class UserPostsController {
    private PostService $postService;

    public function __construct(PostService $postService) {
        $this->postService = $postService;
    }

    public function __invoke(Request $request) {
        $queryOption = QueryOptionFactory::createFromIlluminateRequest($request);

        // explicitly specify the filter names allowed. 
        $queryOption->allowedFilters(['published_date', 'author']);

        $posts = $this->postService->paginate($queryOption);

        // return posts
    }
}

Laravel Bridge

For Laravel applications, you can add Query Option provider inside config/app.php

<?php

use DoneSuperApp\QueryOption\Laravel\QueryOptionProvider;

return [
    // ...
    
    'providers' => [
        // ...
        QueryOptionProvider::class,    
    ],

    // ...
];

After that you can benefit from helpers like:

$queryOption = $request->queryOption();

Inside your repository you can use what we call criterias. Here's an example on how it works:

<?php

use DoneSuperApp\QueryOption\Laravel\UsesQueryOption;

class PostRepository {
    use UsesQueryOption;

    public function paginated(QueryOption $queryOption)
    {
        $query = Post::query();

        [$query, $queryOption] = $this->pipeThroughCriterias($query, $queryOption);

        return $query->paginate(
            $queryOption->getLimit(),
            '*',
            'page',
            $queryOption->getPage()
        );
    }

    protected function getQueryOptionCriterias(): array
    {
        return [
            SearchCriteria::class,
            FilterByPublishedAtCriteria::class,
            SortByCriteria::class
        ];
    }
}

So calling the paginate() method will pass the query through the list of criterias to add the necessary logic for each defined query option. Then, we return the modified query instance to continue the pagination.

Below is the code inside each criteria to illustrate how it works.

class SearchCriteria
{
    public function handle(array $data, Closure $next)
    {
        [$query, $queryOption] = $data;

        $search = $queryOption->getSearch();
        if (!empty($search->getTerm())) {
            if ($search->getType() === 'like') {
                $query->where('title', 'like', "%" . $search->getTerm() . "%");
            }

            if ($search->getType() === 'equal') {
                $query->where('title', '=', $search->getTerm());
            }
        }
        
        return $next([$query, $queryOption]);
    }
}

The search criteria do a search using like or equal using the term when it's not empty, and return the $query and $queryOption for the next criteria.

class SortByCriteria
{
    public function handle(array $data, Closure $next)
    {
        [$query, $queryOption] = $data;

        $sort = $queryOption->getSort();

        // allow sorting only by publish date and title
        if(!in_array($sort->getField(), ['published_date','title'])) {
            return $next([$query, $queryOption]);
        }

        $query->orderBy($sort->getField(), $sort->getDirection());

        return $next([$query, $queryOption]);
    }
}

The sorting is pretty straightforward in this example. An important thing is to guard against sorting using not allowed fields.

class FilterByPublishedAtCriteria
{
    public function handle(array $data, Closure $next)
    {
        [$query, $queryOption] = $data;

        $filter = $queryOption->getFilters()->findByName('publish_date');
        
        $creationDate = Carbon::parse($filter->getValue());
        $query->whereDate('published_at', $filter->getOperator(), $creationDate);

        return $next([$query, $queryOption]);
    }
}

This is it, the pagination will take in consideration the fitering by publish date, searching by title and sorting by publish date.

done-super-app/queryoption 适用场景与选型建议

done-super-app/queryoption 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 10.83k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2025 年 01 月 18 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「search」 「query」 「sort」 「filtering」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 done-super-app/queryoption 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 done-super-app/queryoption 我们能提供哪些服务?
定制开发 / 二次开发

基于 done-super-app/queryoption 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 10.83k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-01-18