PHP code example of gbprod / elastica-specification-bundle

1. Go to this page and download the library: Download gbprod/elastica-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 / elastica-specification-bundle example snippets



// app/AppKernel.php

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



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\Elastica\QueryFactory\Product;

use GBProd\ElasticaSpecification\QueryFactory\Factory;
use GBProd\Specification\Specification;
use Elastica\QueryBuilder;

class IsAvailableFactory implements Factory
{
    public function build(Specification $spec, QueryBuilder $qb)
    {
        return $qb->query()->bool()
            ->addMust()
                $qb->query()->term(['available' => "0"]),
            )
        ;
    }
}



namespace GBProd\Acme\Infrastructure\Product;

use Elastica\Client;
use Elastica\QueryBuilder;
use GBProd\ElasticaSpecification\Handler;
use GBProd\Specification\Specification;

class ElasticaProductRepository implements ProductRepository
{
    private $client;

    private $handler;

    public function __construct(Client $em, Handler $handler)
    {
        $this->client  = $client;
        $this->handler = $handler;
    }

    public function findSatisfying(Specification $specification)
    {
        $type = $this
            ->getIndex('catalog')
            ->getType('product')
        ;

        $query = $this->handler->handle($specification, new QueryBuilder());

        return $type->search($query);
    }
}



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