Skip to content

Latest commit

 

History

History
95 lines (71 loc) · 2.32 KB

simple_usage.md

File metadata and controls

95 lines (71 loc) · 2.32 KB

Simple usage queries

Query, in the CQRS approach, are designed to get the data in the application.

For example, consider the procedure for get an article by identity.

Create a query:

use GpsLab\Component\Query\Query;

class ArticleByIdentityQuery implements Query
{
    public $article_id;
}

You can use private properties to better control the types of data and required properties:

use GpsLab\Component\Query\Query;

class ArticleByIdentityQuery implements Query
{
    private $article_id;

    public function __construct(int $article_id)
    {
        $this->article_id = $article_id;
    }

    public function articleId(): int
    {
        return $this->article_id;
    }
}

Note

To simplify the filling of the query, you can use payload.

You can use any implementations of callable type as a query handler. We recommend using public methods of classes as handlers. For example we use Doctrine ORM.

use GpsLab\Component\Query\Query;
use Doctrine\ORM\EntityManagerInterface;

class ArticleByIdentityHandler
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function handleArticleByIdentity(ArticleByIdentityQuery $query)
    {
        // get article by id
        return $this->em->getRepository(Article::class)->find($query->article_id);
    }
}

And now we register handler and handle query.

use GpsLab\Component\Query\Bus\HandlerLocatedQueryBus;
use GpsLab\Component\Query\Handler\Locator\DirectBindingQueryHandlerLocator;

// register query handler in handler locator
$handler = new ArticleByIdentityHandler($em);
$locator = new DirectBindingQueryHandlerLocator();
$locator->registerHandler(ArticleByIdentityQuery::class, [$handler, 'handleArticleByIdentity']);

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

// ...

// create find article query
$query = new ArticleByIdentityQuery();
$query->article_id = $article_id;

// handle query
$article = $bus->handle($query);

Note

To monitor the execution of commands, you can use middleware.