2014-10-09 1 views
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)); 
} 

같은 것입니다하지만이 가지고 지저분 될 것 많은 경우에 중첩되어 있습니다. 나는 이것이 일반적인 상황이라고 확신하지만 그것을 처리하는 가장 좋은 방법은 확실치 않습니다. 누구에게나 제안 사항이 있거나 형식을 지정하는 더 좋은 방법이 있습니다.

+1

개념을 추상화라고합니다. 큰 문제를 작은 문제로 돌립니다. –

답변

0
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" 
));