gbprod / doctrine-specification-bundle
此包已被废弃,不再维护。未建议替代包。
此包集成了 Doctrine 规范与 Symfony。
v2.1.0
2018-02-09 08:25 UTC
Requires
- php: ^7.0
- doctrine/doctrine-bundle: ^1.5
- gbprod/doctrine-specification: ^2.0
- symfony/doctrine-bridge: ^2.7|^3.0|^4.0
- symfony/expression-language: ^2.7|^3.0|^4.0
- symfony/framework-bundle: ^2.7|^3.0|^4.0
- symfony/yaml: ^2.7|^3.0|^4.0
Requires (Dev)
- phpunit/phpunit: ^6.0|^7.0
This package is auto-updated.
Last update: 2021-01-07 09:39:41 UTC
README
此包集成了 doctrine-specification 与 Symfony。
安装
使用 composer 下载包
composer require gbprod/doctrine-specification-bundle
在您的 app/AppKernel.php
文件中声明
<?php // app/AppKernel.php public function registerBundles() { $bundles = array( // ... new GBProd\DoctrineSpecificationBundle\DoctrineSpecificationBundle(), // ... ); }
创建您的规范和表达式构建器
查看 规范 和 Doctrine 规范 库获取更多信息。
创建规范
<?php namespace GBProd\Acme\CoreDomain\Specification\Product; use GBProd\Specification\Specification; class IsAvailable implements Specification { public function isSatisfiedBy($candidate): bool { return $candidate->isSellable() && $candidate->expirationDate() > new \DateTime('now') ; } }
创建查询工厂
<?php namespace GBProd\Acme\Infrastructure\Doctrine\QueryFactory\Product; use GBProd\DoctrineSpecification\QueryFactory\Factory; use GBProd\Specification\Specification; use Doctrine\ORM\QueryBuilder; class IsAvailableFactory implements Factory { public function create(Specification $spec, QueryBuilder $qb) { return $qb->expr() ->andx( $qb->expr()->eq('sellable', "1"), $qb->expr()->gt('expirationDate', (new \DateTime('now'))->format('c')) ) ; } }
配置
声明您的工厂
# src/GBProd/Acme/AcmeBundle/Resource/config/service.yml services: acme.doctrine.query_factory.is_available: class: GBProd\Acme\Infrastructure\Doctrine\QueryFactory\Product\IsAvailableFactory tags: - { name: doctrine.query_factory, specification: GBProd\Acme\CoreDomain\Specification\Product\IsAvailable }
在您的仓库类中注入处理器
# src/GBProd/Acme/AcmeBundle/Resource/config/service.yml services: acme.product_repository: class: GBProd\Acme\Infrastructure\Product\DoctrineProductRepository arguments: - "@doctrine.orm.entity_manager" - "@gbprod.doctrine_specification_handler"
<?php namespace GBProd\Acme\Infrastructure\Product; use Doctrine\Common\Persistence\ObjectManager; use GBProd\DoctrineSpecification\Handler; use GBProd\Specification\Specification; class DoctrineProductRepository implements ProductRepository { private $em; private $handler; public function __construct(ObjectManager $em, Handler $handler) { $this->em = $em; $this->handler = $handler; } public function findSatisfying(Specification $specification) { $qb = $this ->em ->getRepository('GBProd\Acme\CoreDomain\Product\Product') ->createQueryBuilder('p') ; return $this->handler->handle($specification, $qb); } }
用法
<?php $products = $productRepository->findSatisfying( new AndX( new IsAvailable(), new IsLowStock() ) );