PHP code example of gpslab / specification-query

1. Go to this page and download the library: Download gpslab/specification-query 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/ */

    

gpslab / specification-query example snippets


use GpsLab\Component\Query\Bus\HandlerLocatedQueryBus;
use GpsLab\Component\Query\Handler\Locator\DirectBindingQueryHandlerLocator;
use GpsLab\Component\Query\Specification\SpecificationQueryHandler;
use GpsLab\Component\Query\Specification\ObviousSpecificationQuery;

// register query handler in handler locator
$locator = new DirectBindingQueryHandlerLocator();
$locator->registerHandler(ObviousSpecificationQuery::class, [new SpecificationQueryHandler($em), 'handleSpecification']);

// create bus with query handler locator
$bus = new HandlerLocatedQueryBus($locator);


// specification for get contact with id = 123
$spec = Spec::eq('id', 123);

// cache the result by 1 hour
$modifier = Spec::cache(3600);

// make specification query
$query = new ObviousSpecificationQuery('AcmeDemo:Contact', $spec, $modifier);


// get contact
$contact = $query_bus->handle($query);

class ContactWithIdentityQuery implements SpecificationQuery
{
    /**
     * @var int
     */
    private $id;

    /**
     * @param int $id
     */
    public function __construct($id)
    {
        $this->id = $id;
    }

    /**
     * @return string
     */
    public function entity()
    {
        return 'AcmeDemo:Contact';
    }

    /**
     * @return Specification
     */
    public function spec()
    {
        return Spec::eq('id', $this->id);
    }

    /**
     * @return ResultModifier|null
     */
    public function modifier()
    {
        return Spec::cache(3600);
    }
}

use GpsLab\Component\Query\Bus\HandlerLocatedQueryBus;
use GpsLab\Component\Query\Handler\Locator\DirectBindingQueryHandlerLocator;
use GpsLab\Component\Query\Specification\SpecificationQueryHandler;
use GpsLab\Component\Query\Specification\ObviousSpecificationQuery;

// register query handler in handler locator
$locator = new DirectBindingQueryHandlerLocator();
$locator->registerHandler(ContactWithIdentityQuery::class, [new SpecificationQueryHandler($em), 'handleSpecification']);

// create bus with query handler locator
$bus = new HandlerLocatedQueryBus($locator);


// make specification query
$query = new ContactWithIdentityQuery(123);


// get contact
$contact = $query_bus->handle($query);