2017-10-13 132 views
0

我想檢查用戶是否具有對員工的權限。什麼是在PHP中返回函數的邏輯錯誤的最佳做法

function hasEmployeePermission($employeeID, $userKey) 
{ 
    $usersID = DB::table('users')->where('key', $userKey)->value('id'); 

    if($userID != null) { 
     $employeeID = DB::table('employees')->where('user_id', $userID)->value('id'); 

     if($mployeeID != null) 
      return true; 
     else 
      return false; 
    } 
    return false; 
} 

我想返回值更表現像扔異常。我認爲在邏輯錯誤中拋出異常並不是最佳實踐。我想知道如何修改代碼來返回錯誤。

+0

'返回 「錯誤消息」;'?如果你想讓它在error_log中報告,那麼你可以在返回之前做'error_log(「ERROR MESSAGE」);'。而且你也可以殺死頁面而不是任何回報。 'die(「ERROR MESSAGE」);' – GrumpyCrouton

+5

'hasEmployeePermission'聽起來像是/否問題,所以布爾值可能是最具表現力的事情,您可以使用此函數返回。如果通過錯誤的參數,那麼這是一個例外 – apokryfos

+0

@GrumpyCrouton這可能是危險的,對吧?如果一個編碼器使用if(hasEmployeeAccess())它會通過錯誤情況。 –

回答

0

創建一個簡單的錯誤類。

Class myError{ 
    public $error = true; 
    public $message = null; 
    function __construct($error,$message) { 
     $this->error = $error; 
     $this->message = $message; 
    } 
} 

那麼你可以做這樣的事情,

if($mployeeID != null) 
     return new myError(true,"no permission"); 
    else 
     return new myError(false,"has permission"); 

有可能是添加到類了更多的功能,例如記錄錯誤的地方或類似的東西

0

如果你想知道爲什麼你的功能失敗,在這種情況下,我會建議使用枚舉。

下面是一個例子:

abstract class EmployeeErrors 
{ 
    const WrongID = 1; 
    const NoPermissions = 2; 
    // etc. 
} 

function hasEmployeePermission($employeeID, $userKey) 
{ 
    $usersID = DB::table('users')->where('key', $userKey)->value('id'); 

    if($userID != null) { 
     $employeeID = DB::table('employees')->where('user_id', $userID)->value('id'); 

     if($mployeeID != null) 
      return 0; 
     else 
      if ($userKey == null) 
       return EmployeeErrors::WrongKey; 
      else ... 
    } 
    return EmployeeErrors::WrongID; 
} 
相關問題