如何使用 MVC 架构在 PHP 中抛出错误
我正在尝试重新架构我开发的使用 MVC 模式的 Web 应用程序,但我不确定如何处理错误。例如:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
// Save input
}
}
如果我传递无效的输入来保存,我应该抛出这样的异常:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
if ( ! validate( 'text', $new_data['name'] ) ) {
throw new Exception( 'Invalid data entered' );
}
// Save input
}
}
还是应该添加一个额外的函数并将其留给视图/控制器:
if ( $product->save( $data )->has_error() ) {
$error = $product->get_error();
}
echo '<p>' . $error . '</p>';
I am trying to re-architect a web application I developed to use the MVC pattern, but I'm not sure how to handle errors. For example:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
// Save input
}
}
If I pass invalid input to save, should I throw an exception like this:
class AM_Products extends AM_Object
{
public function save( $new_data = array() )
{
// Validate input
if ( ! validate( 'text', $new_data['name'] ) ) {
throw new Exception( 'Invalid data entered' );
}
// Save input
}
}
Or instead, should I add an extra function and leave it to the view/controller:
if ( $product->save( $data )->has_error() ) {
$error = $product->get_error();
}
echo '<p>' . $error . '</p>';
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要抛出异常。异常是针对特殊情况的 - 输入表单的无效数据不会触发异常。
您的模型应该在模型本身或各个字段上设置某种错误状态。回发应该“失败”并显示与最初显示的表单相同的表单,并带有错误消息和/或突出显示的字段来指示错误所在,以便用户可以修复它。
抛出验证异常将导致系统非常脆弱且难以使用。如果您想要简单地向用户显示他们提供的其中一个字段无效并给他们一个更正的机会,会发生什么情况?您将如何捕获异常并知道如何显示关联的记录/表单?
Don't throw an exception. Exceptions are for exceptional situations - invalid data entered into a form should not trigger an exception.
Your model should have some sort of error state set, either on the model itself or on the individual fields. The post-back should "fall through" and display the same form that was originally shown, with error messages and/or highlighted fields indicating where the error is so the user can fix it.
Throwing exceptions for validation is going to lead to a very fragile and difficult to use system. What happens if you want to simply show the user that one of the fields they supplied is invalid and give them a chance to correct it? How are you going to catch an exception and know how to display the associated record/form?
抛出异常。否则,您必须记住在任何操作后始终调用 has_error/get_error 。而且你会有很多重复的代码。如果错误不应该由调用了
save()
的方法a()
处理,而是由b()
方法处理,该怎么办?调用了方法a()
?您必须从a()
返回错误,并且b()
也必须检查错误。Throw an exception. Otherwise you'll have to remember always to call has_error/get_error after any operation. And you'll have a lot of duplicated code. And what if the error should be handled not by the method
a()
that have calledsave()
, but by the methodb()
that called the methoda()
? you'll have to return error froma()
, andb()
will have to check for the error as well.