CQRS is easy with Symfony 4 and his Messanger Component

Today i want to show you how to use The Messanger Component of Symfony.
Very useful when your project implements the CQRS pattern.

With an example, simplicity of use and practicality will be evident.

Let’s assume that we have a service like this one:

<?php
namespace App\Domain\Service\Customer;
use App\Domain\Command\Customer\DeleteCustomerCommand;
use App\Domain\CommandHandler\Customer\DeleteCustomerCommandHandlerInterface;
use App\Domain\Exception\Customer\CriteriaNotAllowedException;
use App\Domain\Query\Customer\GetCustomerListQuery;
use App\Domain\Query\Customer\GetCustomerQuery;
use App\Domain\QueryHandler\Customer\GetCustomerListQueryHandlerInterface;
use App\Domain\QueryHandler\Customer\GetCustomerQueryHandlerInterface;
class CustomerService implements CustomerServiceInterface
{
/**
* @var GetCustomerListQueryHandlerInterface
*/
private $customerListQueryHandler;
/**
* @var GetCustomerQueryHandlerInterface
*/
private $customerQueryHandler;
/**
* @var DeleteCustomerCommandHandlerInterface
*/
private $deleteCustomerHandler;
    public function __construct(
GetCustomerListQueryHandlerInterface $customerListQueryHandler,
GetCustomerQueryHandlerInterface $customerQueryHandler,
DeleteCustomerCommandHandlerInterface $deleteCustomerHandler
) {
$this->customerListQueryHandler = $customerListQueryHandler;
$this->customerQueryHandler = $customerQueryHandler;
$this->deleteCustomerHandler = $deleteCustomerHandler;
}
    /**
* @param array $criteria
*
* @return mixed
*
* @throws CriteriaNotAllowedException
*/
public function getByCriteria(array $criteria)
{
$getCustomerQueryList = new GetCustomerListQuery();
        foreach ($criteria as $key => $value) {
$method = 'set' . ucfirst($key);
            if (!method_exists($getCustomerQueryList, $method)) {
throw new CriteriaNotAllowedException(sprintf('Parameter %s not allowed', $key));
}
            $getCustomerQueryList->$method($value);
}
        return $this->customerListQueryHandler->handle($getCustomerQueryList);
}
    public function get(string $id)
{
return $this->customerQueryHandler->handle(
new GetCustomerQuery($id)
);
}
    public function delete(string $id)
{
$this->deleteCustomerHandler->handle(
new DeleteCustomerCommand($id)
);
}
}

Continue reading:
https://stefanoalletti.wordpress.com/2018/08/10/cqrs-is-easy-with-symfony-4-and-his-messanger-component/