PHP code example of think-codee / laravel-command-bus
1. Go to this page and download the library: Download think-codee/laravel-command-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/ */
think-codee / laravel-command-bus example snippets
use App\Buses\Query\QueryBusinterface;
class Controller
{
public function __construct(
private QueryBusInterface $queryBus,
) {}
public function show(int $id)
{
$users = $this->queryBus->handle(
new GetUserQuery($id)
);
// Alternatively:
// app('bus.query')->handle(
// new GetUsersQuery()
// );
}
}
use ThinkCodee\Laravel\CommandBus\Contracts\Command;
class GetUserQuery implements Command
{
public function __construct(public int $id) {}
}
class GetUserQueryHandler
{
public function handle(GetUserQuery $query)
{
// Handle the command, e.g., process $query->id
// return User::findOrFail($query->id);
}
}
class LogExceptionsMiddleware
{
public function handle(Command $command, Closure $next)
{
try {
return $next($command);
} catch (\Exception $e) {
Log::error($e->getMessage());
throw $e;
}
}
}
// This will prepend LogExceptionsMiddleware to the existing middleware
#[Middleware([LogExceptionsMiddleware::class], true)]
class StoreUserCommandHandler
{
public function handle(StoreUserCommand $command): int
{
// Handle the command, e.g., process $command->email
// $user = User::create(['email' => $command->email]);
// return $user->id;
}
}
// Handle the command with LogExceptionsMiddleware only
#[ResetMiddleware]
#[Middleware([LogExceptionsMiddleware::class])]
class StoreUserCommandHandler
{
public function handle(StoreUserCommand $command): int
{
// Handle the command, e.g., process $command->email
// $user = User::create(['email' => $command->email]);
// return $user->id;
}
}