CQRS PHP
Command Query Responsibility Segregation PHP

What is CQRS and What Does It Give

To The Code!

Registering Command Handlers

Let's create PlaceOrder Command that will place an order in our system.
1
class PlaceOrder
2
{
3
private string $orderId;
4
private string $productName;
5
6
public function __construct(string $orderId, string $productName)
7
{
8
$this->orderId = $orderId;
9
$this->productName = $productName;
10
}
11
12
public function getOrderId(): string
13
{
14
return $this->orderId;
15
}
16
17
public function getProductName(): string
18
{
19
return $this->productName;
20
}
21
}
Copied!
And Command Handler that will handle this Command
1
use Ecotone\Modelling\Attribute\CommandHandler;
2
3
class OrderService
4
{
5
private array $orders;
6
7
#[CommandHandler]
8
public function placeOrder(PlaceOrder $command) : void
9
{
10
$this->orders[$command->getOrderId()] = $command->getProductName();
11
}
12
}
Copied!

Registering Query Handlers

Let's define GetOrder Query that will find our placed order.
1
class GetOrder
2
{
3
private string $orderId;
4
5
public function __construct(string $orderId)
6
{
7
$this->orderId = $orderId;
8
}
9
10
public function getOrderId(): string
11
{
12
return $this->orderId;
13
}
14
}
Copied!
And Query Handlerthat will handle this query
1
use Ecotone\Modelling\Attribute\CommandHandler;
2
use Ecotone\Modelling\Attribute\QueryHandler;
3
4
class OrderService
5
{
6
private array $orders;
7
8
#[CommandHandler]
9
public function placeOrder(PlaceOrder $command) : void
10
{
11
$this->orders[$command->getOrderId()] = $command->getProductName();
12
}
13
14
#[QueryHandler]
15
public function getOrder(GetOrder $query) : string
16
{
17
if (!array_key_exists($query->getOrderId(), $this->orders)) {
18
throw new \InvalidArgumentException("Order was not found " . $query->getOrderId());
19
}
20
21
return $this->orders[$query->getOrderId()];
22
}
23
}
Copied!

Running The Example

1
$commandBus->send(new PlaceOrder(1, "Milk"));
2
3
echo $queryBus->send(new GetOrder(1));
Copied!

Implementation Using Lite

Last modified 1mo ago