Generate Order Command
<?php | |
namespace App\Services\Cart; | |
use App\Services\Cart\Commands\GenerateOrder; | |
use App\Services\Cart\Commands\GenerateOrderHandler; | |
class CartService { | |
private $bus; | |
private $middleware = [ | |
\App\Services\Cart\Commands\GenerateOrderValidator::class | |
]; | |
public function __construct() | |
{ | |
$this->bus = app('Joselfonseca\LaravelTactician\CommandBusInterface'); | |
} | |
public function generateOrder(array $data = []) | |
{ | |
$this->bus->addHandler(GenerateOrder::class, GenerateOrderHandler::class); | |
return $this->bus->dispatch(GenerateOrder::class, $data, $this->middleware); | |
} | |
} |
<?php | |
namespace App\Services\Cart\Commands; | |
class GenerateOrder { | |
public $user_id; | |
public $payment_method; | |
public $bonus; | |
public $plates; | |
function __construct($user_id, $payment_method, $bonus, $plates) | |
{ | |
$this->user_id = $user_id; | |
$this->payment_method = $payment_method; | |
$this->bonus = $bonus; | |
$this->plates = $plates; | |
} | |
} |
<?php | |
namespace App\Services\Cart\Commands; | |
use DB; | |
use App\Events\OrderWasGenerated; | |
use App\Services\Cart\Models\Order; | |
use Dingo\Api\Exception\ResourceException; | |
class GenerateOrderHandler { | |
public function handle($command) | |
{ | |
DB::beginTransaction(); | |
try{ | |
$order = $this->saveOrder($command); | |
DB::commit(); | |
event(new OrderWasGenerated($command, $order)); | |
return [ | |
'command' => $command, | |
'order' => $order | |
]; | |
}catch (\Exception $e) | |
{ | |
DB::rollBack(); | |
throw new ResourceException($e->getMessage()); | |
} | |
} | |
private function saveOrder($command) | |
{ | |
return Order::create((array) $command); | |
} | |
} |
<?php | |
namespace App\Services\Cart\Commands; | |
use App\Services\Cart\Exceptions\CommandValidationException; | |
use League\Tactician\Middleware; | |
use Validator; | |
class GenerateOrderValidator implements Middleware{ | |
protected $rules = [ | |
'user_id' => 'required', | |
'payment_method' => 'required', | |
'plates' => 'required|array' | |
]; | |
public function execute($command, callable $next) | |
{ | |
$validator = Validator::make((array) $command, $this->rules); | |
if ($validator->fails()) { | |
throw new CommandValidationException($command, $validator); | |
} | |
return $next($command); | |
} | |
} |
This comment has been minimized.
This comment has been minimized.
how i can achieve something like this with this package: https://tactician.thephpleague.com/plugins/command-events/ i want to handle errors. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
I run the bus from a controller and i need to rename
private $middleware
becauseLaravel
uses already this a property with this name and returns an error.