Well, it is technically possible, but would this break the MVC architecture?
I’m not sure whether this type of communication is recommended between both controller and model. I will describe it using a simple example and two ways of doing it:
OPTION 1 (model throws exception and controller catches it):
class Controller {
private $model;
public function save($data) {
try {
$this->model->save($data);
} catch (Exception $e) {
// handle exception
}
}
}
class Model {
public function save($data) {
// Call to internal function to save data in BD
if (! $this->_save($data)) throw new Exception('Error saving data');
}
}
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) {
// handle exception
}
}
}
class Model {
public function save($data) {
// Call to internal function to save data in BD
if (! $this->_save($data)) return false;
}
}
**
EDIT after some responses:
**
These are other ways to solve it based on your suggestions. I hope not to get things too complicated.
OPTION 3 (model handles the exception completely, as Ray said. KingCrunch also suggested to better do it 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 (controller gets a custom child exception thrown 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) {
// handle validation error
}
elseif ($e instanceof DBStorageException) {
// handle DB error
}
}
}
}
class Model {
public function save($data) {
if (! $this->_validate($data)) {
throw new ValidationException ('Validation error');
}
if (! $this->_save($data)) {
throw new DBStorageException ('Storage error');
}
}
}
Model can throw Exception and Controller or View should catch it. Otherwise you never know if everything is working properly down there. So use the first option. But make sure you are throwing properly abstracted Exception that is meaningful to the controller and View.
To illustrate the above bold line see these two throw statements which are used inside a model.
The second example does not show internal error. Rather it hides it. Controller should never know whats happening inside.
In your code your tied a single model to a single controller. Controller does not represent a single model. It uses model. And it can use any number of model. So dont tie up a single model with a controller with variable like
private $model.