frzb / doctrine-specification
Doctrine 仓库的规范模式
v3.0.0
2024-03-24 13:19 UTC
Requires
- php: >=8.0
- doctrine/orm: ~2.5
- symfony/property-access: ^5.4 || ^6.0 || ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.52
- phpspec/phpspec: ~6.3 || ^7.0
README
此库为您提供了编写查询的新方法。通过使用规范模式,您将获得高度可重用的小的规范类。
编写 Doctrine 查询的问题在于,很快就会变得混乱。当您的应用程序增长时,您将在 Doctrine 仓库中拥有 20+ 个函数。所有这些都有长而复杂的 QueryBuilder 调用。您还会发现,您正在使用许多参数来适应不同的用例。
在与 Kacper Gunia 在Sound of Symfony 播客上讨论如何正确测试您的 Doctrine 仓库之后,我们(Kacper 和 Tobias)决定创建这个库。我们受到了 Benjamin Eberlei 在他的博客文章中的想法的启发。
目录
为什么我们需要这个库?
您可能想知道为什么我们创建了此库。您的实体仓库目前运行良好,对吧?
但是,如果您的朋友打开您的仓库类之一,他/她可能会发现代码并不像您想象的那么完美。实体仓库有变得混乱的倾向。可能的问题包括
- 函数太多(例如
findActiveUser
、findActiveUserWithPicture
、findUserToEmail
等) - 一些函数有太多的参数
- 代码重复
- 难以测试
解决方案的要求
该解决方案应具有以下功能
- 易于测试
- 易于扩展、存储和运行
- 可重用代码
- 单一职责原则
- 隐藏 ORM 的实现细节。(这听起来可能有些吹毛求疵,但它会导致客户端代码因为重复进行查询构建工作而变得臃肿。)
实际差异
这是一个如何使用此库的示例。假设您想要获取一些广告并将其关闭。我们应该选择所有那些 endDate
在过去的广告。如果 endDate
为 null,则将其设置为 startDate
后 4 周。
// Not using the lib $qb = $this->em->getRepository('HappyrRecruitmentBundle:Advert') ->createQueryBuilder('r'); return $qb->where('r.ended = 0') ->andWhere( $qb->expr()->orX( 'r.endDate < :now', $qb->expr()->andX( 'r.endDate IS NULL', 'r.startDate < :timeLimit' ) ) ) ->setParameter('now', new \DateTime()) ->setParameter('timeLimit', new \DateTime('-4weeks')) ->getQuery() ->getResult();
// Using the lib $spec = Spec::andX( Spec::eq('ended', 0), Spec::orX( Spec::lt('endDate', new \DateTime()), Spec::andX( Spec::isNull('endDate'), Spec::lt('startDate', new \DateTime('-4weeks')) ) ) ); return $this->em->getRepository('HappyrRecruitmentBundle:Advert')->match($spec);
是的,看起来几乎一模一样。但是后者是可重用的。假设您想要另一个查询来获取我们应关闭的广告,但仅限于特定的公司。
Doctrine Specification
class AdvertsWeShouldClose extends BaseSpecification { public function getSpec() { return Spec::andX( Spec::eq('ended', 0), Spec::orX( Spec::lt('endDate', new \DateTime()), Spec::andX( Spec::isNull('endDate'), Spec::lt('startDate', new \DateTime('-4weeks')) ) ) ); } } class OwnedByCompany extends BaseSpecification { private $companyId; public function __construct(Company $company, ?string $context = null) { parent::__construct($context); $this->companyId = $company->getId(); } public function getSpec() { return Spec::andX( Spec::join('company', 'c'), Spec::eq('id', $this->companyId, 'c') ); } } class SomeService { /** * Fetch Adverts that we should close but only for a specific company */ public function myQuery(Company $company) { $spec = Spec::andX( new AdvertsWeShouldClose(), new OwnedByCompany($company) ); return $this->em->getRepository('HappyrRecruitmentBundle:Advert')->match($spec); } }
QueryBuilder
如果您只是使用 QueryBuilder 来做同样的事情,它将看起来像这样
class AdvertRepository extends EntityRepository { protected function filterAdvertsWeShouldClose(QueryBuilder $qb) { $qb ->andWhere('r.ended = 0') ->andWhere( $qb->expr()->orX( 'r.endDate < :now', $qb->expr()->andX('r.endDate IS NULL', 'r.startDate < :timeLimit') ) ) ->setParameter('now', new \DateTime()) ->setParameter('timeLimit', new \DateTime('-4weeks')) ; } protected function filterOwnedByCompany(QueryBuilder $qb, Company $company) { $qb ->join('company', 'c') ->andWhere('c.id = :company_id') ->setParameter('company_id', $company->getId()) ; } public function myQuery(Company $company) { $qb = $this->em->getRepository('HappyrRecruitmentBundle:Advert')->createQueryBuilder('r'); $this->filterAdvertsWeShouldClose($qb); $this->filterOwnedByCompany($qb, $company); return $qb->getQuery()->getResult(); } }
QueryBuilder 实现的问题在于
- 您只能在 AdvertRepository 中使用
filterOwnedByCompany
和filterAdvertsWeShouldClose
过滤器。 - 您不能使用 And/Or/Not 建立树。例如,如果您想获取所有广告,但不是由 $company 拥有的广告,就没有办法在那种情况下重用
filterOwnedByCompany()
。 - 由于API的创建方式,QueryBuilder过滤的不同部分不能组合在一起。假设我们有一个filterGroupsForApi()调用,无法将其与另一个filterGroupsForPermissions()调用组合。相反,重用此代码将导致创建第三个方法filterGroupsForApiAndPermissions()。
检查单个实体
您可以应用规范来验证特定的实体或数据集。
$highRankFemalesSpec = Spec::andX( Spec::eq('gender', 'F'), Spec::gt('points', 9000) ); // an array of arrays $playersArr = [ ['pseudo' => 'Joe', 'gender' => 'M', 'points' => 2500], ['pseudo' => 'Moe', 'gender' => 'M', 'points' => 1230], ['pseudo' => 'Alice', 'gender' => 'F', 'points' => 9001], ]; // or an array of objects $playersObj = [ new Player('Joe', 'M', 40, 2500), new Player('Moe', 'M', 55, 1230), new Player('Alice', 'F', 27, 9001), ]; foreach ($playersArr as $playerArr) { if ($highRankFemalesSpec->isSatisfiedBy($playerArr)) { // do something } } foreach ($playersObj as $playerObj) { if ($highRankFemalesSpec->isSatisfiedBy($playerObj)) { // do something } }
过滤集合
您可以将规范应用于过滤实体或数据集的集合。
$highRankFemalesSpec = Spec::andX( Spec::eq('gender', 'F'), Spec::gt('points', 9000) ); // an array of arrays $playersArr = [ ['pseudo' => 'Joe', 'gender' => 'M', 'points' => 2500], ['pseudo' => 'Moe', 'gender' => 'M', 'points' => 1230], ['pseudo' => 'Alice', 'gender' => 'F', 'points' => 9001], ]; // or an array of objects $playersObj = [ new Player('Joe', 'M', 40, 2500), new Player('Moe', 'M', 55, 1230), new Player('Alice', 'F', 27, 9001), ]; $highRankFemales = $highRankFemalesSpec->filterCollection($playersArr); $highRankFemales = $highRankFemalesSpec->filterCollection($playersObj); $highRankFemales = $this->em->getRepository(Player::class)->match($highRankFemalesSpec);