我有一个脚本,它运行一堆作业和验证,一旦一切通过,它就会插入并向ajax脚本返回json。
现在我的脚本有点像
$response = "";
if (isset($_POST['upload'])){
// some basic data
// prevent duplicates
if($check_duplicates){
// create json error
$helper->error_duplicate($name);
}
// some more data
// run validation
$validation = $helper->validate_form();
// create json error if fails
if($!$validation){
$helper->error_validation();
}
// validate file
$valid_file = $helper->validate_file();
// create json error if fails
if($!$valid_file){
$helper->error_valid_file();
}
// more data
//execute the insert
$insert_db = $database->execute_statement($insert_array,$file_name,$cleanup=true);
// check if insert was successful
if(!$insert_db){
$response= array(
"result" => "Failure",
"title" => "Database Error",
"message" => "There was an error with the insert"
);
echo (json_encode($response));
}
if($response == ""){
$response= array(
"result" => "Success",
"title" => "Successful Insert",
"message" => "The insert was successful"
);
echo (json_encode($response));
}
}else{
$response= array(
"result" => "Failure",
"title" => "No Access Allow",
"message" => "This page is restricted"
);
echo (json_encode($response));
}
现在,如果前面的一个验证失败,那么就没有必要继续进行其余的验证和插入,但如果有这么多嵌套的if,那就太麻烦了。我确信这是一种常见的情况,但我不确定处理它的最佳方法。有人有什么建议吗?或者有更好的方法来格式化它吗。
if (!$check_duplicates) $helper->error_duplicate($name);
elseif (!$validation = $helper->validate_form()) $helper->error_validation();
elseif (!$valid_file = $helper->validate_file()) $helper->error_valid_file();
elseif (!$insert_db = $database->execute_statement($insert_array,$file_name,$cleanup=true))
echo json_encode(array(
"result" => "Failure",
"title" => "Database Error",
"message" => "There was an error with the insert"
));
else
echo json_encode(array(
"result" => "Success",
"title" => "Successful Insert",
"message" => "The insert was successful"
));