Well, this is technically possible, but will it ruin the MVC architecture?
I am not sure if this type of communication is recommended between the controller and the model. I will describe it with a simple example and two ways to do this:
OPTION 1 (exception of model exceptions and the controller catches it):
class Controller { private $model; public function save($data) { try { $this->model->save($data); } catch (Exception $e) {
OPTION 2 (the controller handles the exception completely):
class Controller { private $model; public function save($data) { try { if (! $this->model->save($data)) throw new Exception('Error saving data'); } catch (Exception $e) {
**
EDIT after some answers:
**
These are other ways to solve this problem based on your suggestions. I hope this is not too difficult.
OPTION 3 (the model handles the exception completely, as Ray said. KingCrunch also suggested a better way to do this in the model)
class Controller { private $model; public function save($data) { if (! $this->model->save($data)) { // possible action: redirect to the form with an error message } } } class Model { public function save($data) { try { if (! $this->_save($data)) throw new Exception('Error saving data'); } catch (Exception $e) { // handle exception return false; } return true; } }
OPTION 4 (the controller receives a custom child exception generated by the model, as shiplu.mokadd.im said).
class Controller { private $model; public function save($data) { try { $this->model->save($data); } catch (Exception $e) { if ($e instanceof ValidationException) {
php exception model-view-controller controller model
Luis martin
source share