0
我有一個腳本,它運行一堆作業和驗證,一旦所有東西都通過,它會執行插入操作並將json返回給ajax腳本。PHP - 錯誤處理的結構
現在,我的劇本是這樣的
$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。我確定這是一種常見情況,但我不確定處理它的最佳方式。有沒有人有任何建議,或有更好的方式來格式化。
該概念被稱爲抽象。將大問題分解爲更小的問題。 – 2014-10-09 20:38:29