PHP code example of remotelyliving / php-query-bus
1. Go to this page and download the library: Download remotelyliving/php-query-bus 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/ */
remotelyliving / php-query-bus example snippets
$resolver = Resolver::create($serviceContainer) // can locate in service container
->pushHandler(GetUserProfileQuery::class, new GetUserProfileHandler()) // can locate in a local map {query => handler}
->pushHandlerDeferred(GetUserQuery::class, $lazyCreateMethod); // can locate deferred to save un unnecessary object instantiation
class GetUserQuery
{
private bool $shouldIncludeProfile = false;
private string $userId;
public function __construct(string $userId)
{
$this->userId = $userId;
}
public function getUserId(): string
{
return $this->userId;
}
public function
class GetUserResult extends AbstractResult implements \JsonSerializable
{
private User $user;
private ?UserProfile $userProfile;
public function __construct(User $user, ?UserProfile $userProfile)
{
$this->user = $user;
$this->userProfileResult = $userProfile;
}
public function getUser(): User
{
return $this->user;
}
public function getUserProfile(): ?UserProfile
{
return $this->userProfile;
}
public function jsonSerialize(): array
{
return [
'user' => $this->getUser(),
'profile' => $this->getUserProfile(),
];
}
}
class GetUserHandler implements Interfaces\Handler
{
public function handle(object $query, Interfaces\QueryBus $bus): Interfaces\Result
{
try {
$user = $this->userRepository->getUserById($query->getUserId());
} catch (ConnectectionError $e) {
// can handle exceptions without blowing up and instead use messaging via
// AbstractResult::getErrors(): \Throwable[] and AbstractResult::hasErrors(): bool
return AbstractResult::withErrors($e);
}
if (!$user) {
// can handle nullish cases by returning not found
return AbstractResult::notFound();
}
if (!$query->shouldIncludeProfile()) {
return new GetUserResult($user, null);
}
$profileResult = $bus->handle(new GetUserProfileQuery($query->getUserId()));
return ($profileResult->isNotFound())
? new GetUserResult($user, null)
: new GetUserResult($user, $profileResult->getUserProfile());
}
}
$cachingMiddleware = function (object $query, callable $next) use ($queryCacher) : Interfaces\Result {
if ($query instanceof Interfaces\CacheableQuery) {
return $queryCacher->get($query, function () use ($next, $query) { return $next($query); });
}
return $next($query);
};
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.