artprima/query-filter-bundle
Composer 安装命令:
composer require artprima/query-filter-bundle
包简介
An easy way to filter requests in your Symfony 4/5/6 application (that uses Doctrine2 as ORM).
README 文档
README
| Master |
|---|
Query Filter Bundle for Symfony 4.4, Symfony 5 and Symfony 6
Query Filter Bundle brings request filtering and pagination functionality to Symfony 4.4 / 5 / 6 applications that use Doctrine 2.
Installation
First, install the dependency:
$ composer require artprima/query-filter-bundle
Usage examples
Basic example
- Controller
<?php namespace App\Controller; use Artprima\QueryFilterBundle\QueryFilter\Config\BaseConfig; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Component\HttpFoundation\Request as HttpRequest; use Artprima\QueryFilterBundle\Request\Request; use Artprima\QueryFilterBundle\QueryFilter\QueryFilter; use Artprima\QueryFilterBundle\Response\Response; use App\Repository\ItemRepository; class DefaultController extends Controller { // ... /** * @Route("/") */ public function indexAction(HttpRequest $request, ItemRepository $repository) { // set up the config $config = new BaseConfig(); $config->setSearchAllowedCols(['t.name']); $config->setSearchAllowedColsLengths(['t.name' => ['min' => 2, 'max' => 255]]); $config->setAllowedLimits([10, 25, 50, 100]); $config->setDefaultLimit(10); $config->setSortCols(['t.id'], ['t.id' => 'asc']); $config->setRequest(new Request($request)); // Throws an UnexpectedValueException when invalid filter column, sort column or sort type is specified $config->setStrictColumns(true); // here we provide a repository callback that will be used internally in the QueryFilter // The signature of the method must be as follows: function functionName(QueryFilterArgs $args): QueryResult; $config->setRepositoryCallback([$repository, 'findByOrderBy']); // Response must implement Artprima\QueryFilterBundle\Response\ResponseInterface $queryFilter = new QueryFilter(Response::class); /** @var Response $data the type of the variable is defined by the class in the first argument of QueryFilter's constructor */ $response = $queryFilter->getData($config); $data = $response->getData(); $meta = $response->getMeta(); // ... now do something with $data or $meta } // ... }
- Repository
<?php namespace App\Repository; use App\Entity\Item; use Artprima\QueryFilterBundle\Query\ConditionManager; use Artprima\QueryFilterBundle\QueryFilter\QueryFilterArgs; use Artprima\QueryFilterBundle\QueryFilter\QueryResult; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\Tools\Pagination\Paginator; use Symfony\Bridge\Doctrine\RegistryInterface; class ItemRepository extends ServiceEntityRepository { /** * @var ConditionManager */ private $pqbManager; public function __construct(RegistryInterface $registry, ConditionManager $manager) { parent::__construct($registry, Item::class); $this->pqbManager = $manager; } public function findByOrderBy(QueryFilterArgs $args): QueryResult { // Build our request $qb = $this->createQueryBuilder('t') ->setFirstResult($args->getOffset()) ->setMaxResults($args->getLimit()); $proxyQb = $this->pqbManager->wrapQueryBuilder($qb); $qb = $proxyQb->getSortedAndFilteredQueryBuilder($args->getSearchBy(), $args->getSortBy()); $query = $qb->getQuery(); $paginator = new Paginator($query); // return the wrapped result return new QueryResult($paginator->getIterator()->getArrayCopy(), count($paginator)); } // ... }
Now you can start your php server and filter the requests:
GET http://127.0.0.1:8000/?filter[t.name]=Doe&limit=100
This request will perform a LIKE request in DQL:
SELECT t FROM Item WHERE t.name LIKE "%Doe%" LIMIT 100
Advanced example
This filtering library is best used together with JMSSerializerBundle and FOSRestBundle. You will eventually write a lot less code that it was shown in the basic example.
To utilize the advanced usage, install all the packages.
composer require friendsofsymfony/rest-bundle composer require jms/serializer-bundle composer require artprima/query-filter-bundle
- Turn them on in
config/bundles.php:
<?php return [ // ... Artprima\QueryFilterBundle\ArtprimaQueryFilterBundle::class => ['all' => true], FOS\RestBundle\FOSRestBundle::class => ['all' => true], JMS\SerializerBundle\JMSSerializerBundle::class => ['all' => true], // ... ];
NOTE: you may need to add further bundles depending on your set up for FOSRestBundle and/or JMSSerializerBundle.
- Controller:
<?php namespace App\Controller; use App\QueryFilter\Response; use App\Repository\ItemRepository; use Artprima\QueryFilterBundle\QueryFilter\Config\ConfigInterface as QueryFilterConfigInterface; use FOS\RestBundle\Controller\Annotations as Rest; use FOS\RestBundle\Controller\FOSRestController; use FOS\RestBundle\Routing\ClassResourceInterface; use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter; use Artprima\QueryFilterBundle\Controller\Annotations\QueryFilter; class ItemController extends FOSRestController implements ClassResourceInterface { /** * @Rest\View(serializerEnableMaxDepthChecks=true) * @ParamConverter("config", class="App\QueryFilter\Config\ItemConfig", * converter="query_filter_config_converter", * options={"entity_class": "App\Entity\Item", "repository_method": "findByOrderBy"}) * @QueryFilter() * @Rest\Get("/items") */ public function cgetAction(QueryFilterConfigInterface $config) { return $config; } }
- Repository:
<?php namespace App\Repository; use App\Entity\Item; use Artprima\QueryFilterBundle\Query\ConditionManager; use Artprima\QueryFilterBundle\QueryFilter\QueryFilterArgs; use Artprima\QueryFilterBundle\QueryFilter\QueryResult; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\ORM\Tools\Pagination\Paginator; use Symfony\Bridge\Doctrine\RegistryInterface; /** * @method Item|null find($id, $lockMode = null, $lockVersion = null) * @method Item|null findOneBy(array $criteria, array $orderBy = null) * @method Item[] findAll() * @method Item[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class ItemRepository extends ServiceEntityRepository { /** * @var ConditionManager */ private $pqbManager; public function __construct(RegistryInterface $registry, ConditionManager $manager) { parent::__construct($registry, Item::class); $this->pqbManager = $manager; } public function findByOrderBy(QueryFilterArgs $args): QueryResult { $qb = $this->createQueryBuilder('t') ->setFirstResult($args->getOffset()) ->setMaxResults($args->getLimit()); $proxyQb = $this->pqbManager->wrapQueryBuilder($qb); $qb = $proxyQb->getSortedAndFilteredQueryBuilder($args->getSearchBy(), $args->getSortBy()); $query = $qb->getQuery(); $paginator = new Paginator($query); return new QueryResult($paginator->getIterator()->getArrayCopy(), count($paginator)); } }
ItemConfig:
<?php namespace App\QueryFilter\Config; use Artprima\QueryFilterBundle\QueryFilter\Config\BaseConfig; class ItemConfig extends BaseConfig { public function __construct() { $this->setSearchAllowedCols([ 't.name', ]); $this->setSortCols( ['t.id'], ['t.id' => 'desc'] // default ); } }
Simple Query Filter Examples
NOTE: assume that all the used fields are enabled in the configuration
- Performs
t.name LIKE%doe% comparison - Performs
t.name = "Doe"comparison - Performs
t.name <> "Doe"comparison - Performs
t.name LIKE "Doe"comparison - Performs
t.name NOT LIKE "Doe"comparison - Performs
t.frequency BETWEEN 8 AND 10comparison - Performs
t.frequency NOT BETWEEN 8 AND 10comparison - Performs
t.frequency > 7comparison - Performs
t.frequency >= 7comparison - Performs
t.frequency IN (1, 2, 3, 4, 5)comparison - Performs
t.frequency NOT IN (1, 2, 3, 4, 5)comparison - Performs
t.description IS NULLcomparison - Performs
t.description IS NOT NULLcomparison - Performs
t.frequency < 7comparison - Performs
t.frequency <= 7comparison - Combined comparison
t.frequency < 7 AND t.monetary > 50
Advanced Query Filter Example
Simple mode should be enough for most of the cases, however sometimes we might need to build more complicated filters having one and the same field used.
- Performs
t.frequency = 10 OR t.frequency >= 85(NOTE:filter[1][connector]=or-connectorcan beand(default) oror; connector used on the first filter has no effect)
Pagination Examples
- Second page (NOTE: if
pageis not given it defaults to 1) - Limit records to 100 (NOTE: if default limits were provided and
limitis not within the allowed values, it will be reset to the default value)
Sorting Example
- Performs
ORDER BY t.userId DESC(ifsortdiris not given it defaults toasc)
NOTE: at the moment this bundle doesn't support more than one field for ORDER BY.
This document is not finished yet, more examples will follow.
Code license
You are free to use the code in this repository under the terms of the MIT license. LICENSE contains a copy of this license.
artprima/query-filter-bundle 适用场景与选型建议
artprima/query-filter-bundle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 30.5k 次下载、GitHub Stars 达 28, 最近一次更新时间为 2018 年 03 月 08 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「symfony」 「doctrine」 「filter」 「query」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 artprima/query-filter-bundle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 artprima/query-filter-bundle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 artprima/query-filter-bundle 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Nova searchable filter for belongsTo relationships.
The bundle for easy using json-rpc api on your project
Symfony DataGridBundle
Make pimcore migration simple
Bundle Symfony DaplosBundle
Data provider for yii2
统计信息
- 总下载量: 30.5k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 28
- 点击次数: 2
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2018-03-08