The way I am doing this now is as follows (sorry long post).
public function createAction($title, $content) { try { $post = $this->commandBus->execute(new CreatePostCommand($title, $content); } catch (Exception $e) { return $this->render('some error template file', $e); } return $this->render('successful creation template file', $post); }
This way you create the message, and if everything goes as planned, return the $ post object and send it to your view. On the other hand, when an exception is thrown at runtime, you detect this error and send it to the view.
My preferred way is to force the controller to call a method for the service that controls this behavior, and introduce the controller as a listener that manages the responses, i.e.:
public function createAction($title, $content) { $service = new CreateActionService($title, $content); return $service->create($this); } public function onError(Exception $e) { return $this->render('some error template file', $e); } public function onSuccess($post) { return $this->render('success', $post); }
Then at your service ...
public function create($listener) { try { $this->commandBus->execute(new CreatePostCommand($title, $content); } catch (Exception $e) { return $this->listener->onError($e); } return $this->listener->onSuccess($post); }
In this way, your service manages the various results that the command handler can return, and your controller remains just to manage the responses that you might want to return to the presentation level.
source share