2017-10-13 129 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; 
} 
相关问题