Let's say I run a clothing web shop. I have an order form that my customers can place orders. A customer fills out their order for a t-shirt and submits the form. The problem is the t-shirt is out of stock.
This isn't a validation issue, because the order was valid, so i wouldn't create a custom validator.
I'm using the FOSRestBundle and trying to support both HTML and JSON. I'm also trying to accomplish a lot through domain events.
Here's my pseudo coded controller
class OrderController extends BaseOrderController
{
public function createAssetAction(Request $request)
{
$form = $this->getOrderCreateForm();
$form->handleRequest($request);
if ($form->isValid()) {
// should i wrap this in a try/catch?
$this->dispatch(OrderEvents::PRE_CREATE, $event = new FormEvent($form, $form->getData()));
// or check if the event is stopped and pull out an error message?
if ($order = $event->getData()) {
$this->getOrderRepository()->persist($order);
$this->dispatch(OrderEvents::POST_CREATE, new ResourceEvent($order));
$view = $this->routeRedirectView('my_orders', array(), Codes::HTTP_MOVED_PERMANENTLY);
$view->setData(array('order' => $order));
return $this->handleView($view);
}
}
$view = $this->view($form)
->setTemplateVar('form')
->setTemplate('OrderBundle:Order:newOrder.html.twig');
return $this->handleView($view);
}
}
I'm thinking i would check the inventory of the order in the OrderEvents::PRE_CREATE
event. I don't know whether to throw an exception in an event listener if there is insufficient stock or stop the event propagation and add a message to the event.
If i threw an exception, i'd have to catch it in the controller so i could set the exception message as a flash message for an HTML request or just return the message directly for a JSON response.
If i did that, i'd have to wrap all event dispatching in the controller in try/catches, which seems wrong.
I've seen the LiipCacheControl bundle which converts flash messages to a cookie but that introduces state into my stateless REST API.
Anybody have suggestions?