1. Go to this page and download the library: Download spiral-packages/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/ */
class StoreUser implements \Spiral\Cqrs\CommandInterface
{
public function __construct(
public Uuid $uuid,
public string $username,
public string $password,
public \DateTimeImmutable $registeredAt,
) {
}
}
class StoreUserHandler
{
public function __construct(
private EntityManagerInterface $entityManager
) {
}
#[\Spiral\Cqrs\Attribute\CommandHandler]
public function __invoke(StoreUser $command)
{
$this->entityManager->persist(
new User(
$command->uuid,
$command->username,
$command->password,
$command->registeredAt
)
);
$this->entityManager->run();
}
}
use Ramsey\Uuid\Uuid;
class UserController
{
public function store(UserStoreRequest $request, \Spiral\Cqrs\CommandBusInterface $bus)
{
$bus->dispatch(new StoreUser(
$uuid = Uuid::uuid4(),
$request->getUsername(),
$request->getPassword(),
new \DateTimeImmutable()
));
return $uuid;
}
}
class FindAllUsers implements \Spiral\Cqrs\QueryInterface
{
public function __construct(
public array $roles = []
) {
}
}
class FindUserById implements \Spiral\Cqrs\QueryInterface
{
public function __construct(
public Uuid $uuid
) {
}
}
class UsersQueries
{
public function __construct(
private UserRepository $users
) {
}
#[\Spiral\Cqrs\Attribute\QueryHandler]
public function findAll(FindAllUsers $query): UserCollection
{
$scope = [];
if ($query->roles !== []) {
$scope['roles'] = $query->roles
}
return new UserCollection(
$this->users->findAll($scope)
);
}
#[\Spiral\Cqrs\Attribute\QueryHandler]
public function findById(FindUserById $query): UserResource
{
return new UserResource(
$this->users->findByPK($query->uuid)
);
}
}
use Ramsey\Uuid\Uuid;
class UserController
{
public function index(UserFilters $filters, \Spiral\Cqrs\QueryBusInterface $bus)
{
return $bus->ask(
new FindAllUsers($filters->roles())
)->toArray();
}
public function show(string $uuid, \Spiral\Cqrs\QueryBusInterface $bus)
{
return $bus->ask(
new FindUserById(Uuid::fromString($uuid))
)->toArray();
}
}
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.