Skip to content

Instantly share code, notes, and snippets.

@joselfonseca
Created September 8, 2015 15:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joselfonseca/24ee0e96666a06b16f92 to your computer and use it in GitHub Desktop.
Save joselfonseca/24ee0e96666a06b16f92 to your computer and use it in GitHub Desktop.
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);
}
}
@ralbear
Copy link

ralbear commented Nov 16, 2019

I run the bus from a controller and i need to rename private $middleware because Laravel uses already this a property with this name and returns an error.

@shift14wx
Copy link

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