好吧,这在技术上是可行的,但这会破坏 MVC 架构吗?
我不确定控制器和模型之间是否建议使用这种类型的通信。我将使用一个简单的示例和两种方法来描述它:
选项 1(模型抛出异常并且控制器捕获它):
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');
}
}
选项 2(控制器完全处理异常):
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;
}
}
**
一些回应后编辑:
**
这些是根据您的建议解决问题的其他方法。我希望不要把事情弄得太复杂。
选项 3(模型完全处理异常,正如 Ray 所说。KingCrunch 还建议在模型中更好地做到这一点)
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;
}
}
选项 4(控制器获取模型抛出的自定义子异常,如 shiplu.mokadd.im 所说。)
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');
}
}
}