承接 ttskch/doctrine-orm-criteria 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

ttskch/doctrine-orm-criteria

Composer 安装命令:

composer require ttskch/doctrine-orm-criteria

包简介

Doctrine ORM Criteria allows you to separate any complex "search condition" as a Criteria with a specialized API for QueryBuilder of doctrine/orm.

README 文档

README

codecov Latest Stable Version Total Downloads

Motivation

QueryBuilder of doctrine/orm has a method called addCriteria() that allows you to build queries by combining Criteria of doctrine/collections. This allows you to separate the concerns of "search conditions" into a Criteria, improving the maintainability of your codebase.

However, Criteria of doctrine/collections only has a very limited matching language because it is designed to work both on the SQL and the PHP collection level, and therefore cannot be used to build complex queries.

Rejoice! Doctrine ORM Criteria allows you to separate any complex "search condition" as a Criteria with a specialized API for QueryBuilder of doctrine/orm just like below.

$qb = (new CriteriaAwareness($fooRepository->createQueryBuilder('f')))
    ->addCriteria(new IsPublic(), 'f')
    ->addCriteria(new IsAccessibleBy($user), 'f')
    ->addCriteria(new CategoryIs($category), 'f')
    ->addCriteria(new OrderByRandom(), 'f')
    ->getQueryBuilder()
;
$foos = $qb->getQuery()->getResult();

// Or, using the Repository integration:

$foos = $fooRepository->findByCriteria([
    new IsPublic(),
    new IsAccessibleBy($user),
    new CategoryIs($category),
    new OrderByRandom(),
]);
final readonly class IsPublic implements CriteriaInterface
{
    public ?\DateTimeInterface $at;

    public function __construct(?\DateTimeInterface $at = null)
    {
        $this->at = $at ?? new \DateTimeImmutable();
    }

    public function apply(QueryBuilder $qb, string $alias): void
    {
        $qb
            ->andWhere("$alias.state = :state")
            ->andWhere($qb->expr()->andX(
                $qb->expr()->orX(
                    "$alias.openedAt IS NULL",
                    "$alias.openedAt <= :at",
                ),
                $qb->expr()->orX(
                    "$alias.closedAt IS NULL",
                    "$alias.closedAt > :at",
                ),
            ))
            ->setParameter('state', Foo::STATE_PUBLIC)
            ->setParameter('at', $this->at)
        ;
    }
}

Requirements

  • PHP: ^8.1
  • Doctrine ORM: ^2.8|^3.0

Installation

$ composer require ttskch/doctrine-orm-criteria

Usage

Basic

You can create your own Criteria by implementing CriteriaInterface and adding it to CriteriaAwareness to build queries.

use App\Repository\Criteria\Foo\IsPublic;
use Ttskch\DoctrineOrmCriteria\CriteriaAwareness;

$qb = (new CriteriaAwareness($fooRepository->createQueryBuilder('f')))
    ->addCriteria(new IsPublic(), 'f')
    ->getQueryBuilder()
;
<?php

declare(strict_types=1);

namespace App\Repository\Criteria\Foo;

final readonly class IsPublic implements CriteriaInterface
{
    public ?\DateTimeInterface $at;

    public function __construct(?\DateTimeInterface $at = null)
    {
        $this->at = $at ?? new \DateTimeImmutable();
    }

    public function apply(QueryBuilder $qb, string $alias): void
    {
        $qb
            ->andWhere("$alias.state = :state")
            ->andWhere($qb->expr()->andX(
                $qb->expr()->orX(
                    "$alias.openedAt IS NULL",
                    "$alias.openedAt <= :at",
                ),
                $qb->expr()->orX(
                    "$alias.closedAt IS NULL",
                    "$alias.closedAt > :at",
                ),
            ))
            ->setParameter('state', Foo::STATE_PUBLIC)
            ->setParameter('at', $this->at)
        ;
    }
}

Built-in Criteria and utilities

There are some built-in Criteria: OrderBy, Andx, and Orx. Using Andx and Orx, you can combine multiple Criteria to create a new Criteria.

<?php

declare(strict_types=1);

namespace App\Repository\Criteria\Foo;

use App\Entity\User;
use Doctrine\ORM\QueryBuilder;
use Ttskch\DoctrineOrmCriteria\Criteria\CriteriaInterface;
use Ttskch\DoctrineOrmCriteria\Criteria\Andx;
use Ttskch\DoctrineOrmCriteria\Criteria\Orx;

final readonly class IsViewable implements CriteriaInterface
{
    public ?\DateTimeInterface $at;

    public function __construct(
        public User $me,
        ?\DateTimeInterface $at = null,
    ) {
        $this->at = $at ?? new \DateTimeImmutable();
    }

    public function apply(QueryBuilder $qb, string $alias): void
    {
        (new Andx([
            new Orx([
                new IsPublic($this->at),
                ...array_map(fn (string $category) => new CategoryIs($category), Foo::PUBLIC_CATEGORIES),
            ]),
            new IsAccessibleBy($this->me),
        ]))->apply($qb, $alias);
    }
}

Additionally, when creating your own Criteria, you can use AddSelectTrait and JoinTrait to ensure that the addSelect() and join are IDEMPOTENT even if the Criteria is applied multiple times to the QueryBuilder.

<?php

declare(strict_types=1);

namespace App\Repository\Criteria\Foo;

use App\Entity\User;
use Doctrine\ORM\QueryBuilder;
use Ttskch\DoctrineOrmCriteria\Criteria\CriteriaInterface;
use Ttskch\DoctrineOrmCriteria\Criteria\Traits\JoinTrait;

final readonly class IsAccessibleBy implements CriteriaInterface
{
    use JoinTrait;

    private const string CRITERIA_KEY = 'Foo_IsAccessibleBy'; // some unique key

    public function __construct(public User $me)
    {
    }

    public function apply(QueryBuilder $qb, string $alias): void
    {
        $userAlias = sprintf('%s_%s_user', self::CRITERIA_KEY, $alias);

        $this->leftJoin($qb, sprintf('%s.user', $alias), $userAlias);

        $qb
            ->andWhere(sprintf('%s = :user', $userAlias))
            ->setParameter('user', $this->me)
        ;
    }
}

Integration with Repository

You can also easily integrate with your repositories using CriteriaAwareRepositoryTrait.

  <?php

  declare(strict_types=1);

  namespace App\Repository;

  use App\Entity\Foo;
  use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
  use Doctrine\Persistence\ManagerRegistry;
+ use Ttskch\DoctrineOrmCriteria\Repository\CriteriaAwareRepositoryTrait;

  /**
   * @extends ServiceEntityRepository<Foo>
   */
  class FooRepository extends ServiceEntityRepository
  {
+     /** @use CriteriaAwareRepositoryTrait<Foo> */
+     use CriteriaAwareRepositoryTrait;
+
      public function __construct(ManagerRegistry $registry)
      {
          parent::__construct($registry, Foo::class);
      }
  }
$foos = $fooRepository->findByCriteria([
    new IsPublic(),
    new IsAccessibleBy($user),
    new CategoryIs($category),
    new OrderByRandom(),
]);

\PHPStan\dumpType($foos); // Dumped type: array<App\Entity\Foo>

$foo = $fooRepository->findOneByCriteria([
    new IsPublic(),
    new IsAccessibleBy($user),
    new CategoryIs($category),
    new OrderByRandom(),
]);

\PHPStan\dumpType($foo); // Dumped type: App\Entity\Foo|null

$count = $fooRepository->countByCriteria([
    new IsPublic(),
    new IsAccessibleBy($user),
    new CategoryIs($category),
]);

\PHPStan\dumpType($count); // Dumped type: int

Getting involved

$ composer install

# Develop...

$ composer tests

ttskch/doctrine-orm-criteria 适用场景与选型建议

ttskch/doctrine-orm-criteria 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 5.36k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2024 年 08 月 22 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 ttskch/doctrine-orm-criteria 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 5.36k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 17
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

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

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-08-22