PHP code example of gbprod / doctrine-specification-bundle

1. Go to this page and download the library: Download gbprod/doctrine-specification-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gbprod / doctrine-specification-bundle example snippets



// app/AppKernel.php

public function registerBundles()
{
    $bundles = array(
        // ...
        new GBProd\DoctrineSpecificationBundle\DoctrineSpecificationBundle(),
        // ...
    );
}



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')
        ;
    }
}



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'))
            )
        ;
    }
}



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);
    }
}



$products = $productRepository->findSatisfying(
    new AndX(
        new IsAvailable(),
        new IsLowStock()
    )
);