How to throw errors in PHP using an MVC Architecture
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
开发者_C百科 }
}
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>';
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?
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 called save()
, but by the method b()
that called the method a()
? you'll have to return error from a()
, and b()
will have to check for the error as well.
精彩评论