2013-11-20 44 views
0

我有一個圖像上傳的形式,我上傳文件之前調用多個函數,如檢查大小,尺寸和它是一個有效的圖像。代碼的作品,但調用的功能和處理結果似乎相當繁瑣和複雜。調用多個PHP函數 - 最佳實踐

是否有一種結構化代碼的更加整潔的方式。

這是我目前有:

if(checkvalidfile("img",$ext)){ 
    if(checksize($size, 524288)) { 
     if(checkdimensions($tmp, 300)) { 
      $newfilename = renamefile($ext); 
      uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3); 
      header('Location: ./message.php?action=newlogo'); 
     } else { 
     echo "Your image can't be bigger than 300 x 300px"; 
     die; 
     } 
    } else { 
    echo "File size is too big!"; 
    die; 
    } 
} else { 
echo "Not a valid file"; 
die; 
} 
+0

此處不討論話題。嘗試http://codereview.stackexchange.com – meagar

+0

這是更適合codereview.stackexchange.com –

+4

此問題似乎是脫離主題,因爲它是一個代碼審查請求。這更適合http://codereview.stackexchange.com –

回答

1

沒有必要else因爲你die ING。與!否定了你的條件和UNNEST他們都:

if(!checkvalidfile("img",$ext)){ 
    echo "Error message"; 
    die; 
} 

if(!checksize($size, 524288)) { 
    echo "error message"; 
    die; 
} 

if(!checkdimensions($tmp, 300)) { 
    echo "Error message"; 
    die; 
} 

$newfilename = renamefile($ext); 
uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3); 
header('Location: ./message.php?action=newlogo'); 

如果您認爲die不這樣做(這絕對不是,這是一個非常糟糕的用戶體驗),那麼你可以把你的條件,在一個正確的事單功能失敗時返回錯誤消息,或者成功時返回false

function checkValid() { 
    if(!checkvalidfile("img",$ext) 
    return "Error message 1"; 

    if(!checksize($size, 524288)) 
    return "error message 2"; 

    if(!checkdimensions($tmp, 300)) 
    return "error message 3"; 

    return false; 
} 


if ($error = checkValid()) { 
    echo $error; 
} else { 

    $newfilename = renamefile($ext); 
    uploadfile($tmp, $bucket, "user_docs/agency_".$agency_id."/brand_logos/", $newfilename, $s3); 
    header('Location: ./message.php?action=newlogo'); 
}