1. Go to this page and download the library: Download zaw/attribute-driven-cqrs 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/ */
zaw / attribute-driven-cqrs example snippets
use Zaw\AttributeDrivenCqrs\CommandBus;
use Zaw\AttributeDrivenCqrs\Attributes\HandleCommandWith;
#[HandleCommandWith(CreateUserHandler::class)]
class CreateUserCommand
{
public function __construct(private string $username, private string $email) {}
public function getUserName(): string
{
return $this->username;
}
public function getEmail(): string
{
return $this->email;
}
}
class CreateUserHandler
{
public function handle(object $command): void
{
echo "User '{".$command->getUserName()."}' created with email '{".$command->email."}'";
}
}
$command = new CreateUserCommand('JohnDoe', '[email protected]');
CommandBus::getInstance()->handle($command);
use Zaw\AttributeDrivenCqrs\QueryBus;
use Zaw\AttributeDrivenCqrs\Attributes\HandleQueryWith;
#[HandleQueryWith(GetUserHandler::class)]
class GetUserQuery {
public function __construct(private int $userId) {}
public function getUserId()
{
return $this->userId;
}
}
class GetUserHandler {
public function handle(object $query)
{
return $userService->getUser($query->getUserId());
}
}
$query = new GetUserQuery(1);
$result = QueryBus::getInstance()->handle($query);
use Psr\Log\LoggerInterface;
class CreateUserHandler {
private LoggerInterface $logger;
// Services or other dependencies can be injected via the constructor
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function handle(CreateUserCommand $command): void
{
$this->logger->info("Creating user '{$command->getUserName()}'");
echo "User '{$command->getUserName()}' created with email '{$command->getEmail()}'";
}
}
class GetProductHandler {
private ProductService $productService;
// Dependency injection of the ProductService
public function __construct(ProductService $productService)
{
$this->productService = $productService;
}
public function handle(GetProductQuery $query): Product
{
return $this->productService->getProduct($query->getProductId());
}
}
use Zaw\AttributeDrivenCqrs\Attributes\BeforeHandle;
use Zaw\AttributeDrivenCqrs\Attributes\AfterHandle;
use Zaw\AttributeDrivenCqrs\Middlewares\Interfaces\MiddlewareInterface;
#[BeforeHandle(LoggingMiddleware::class)]
#[HandleCommandWith(CreateUserHandler::class)]
class CreateUserCommand {
public function __construct(private string $username, private string $email) {}
}
class LoggingMiddleware implements MiddlewareInterface
{
public function process($command, $result)
{
echo "Logging: Command " . get_class($command) . " is being processed.";
}
}