检查是否为空或使用 try/catch?

Checking if empty or using a try/catch?

我正在 Laravel 5 中启动一个应用程序,我对这个框架还比较陌生。我正在检查用户的唯一密钥是否在请求中,我要问的问题可能跨框架。我正在查询数据库并使用 firstOrFail。我想知道使用 try/catch 并捕获错误或检查是否为空是否有任何优势?

try {
    User::where('identifier', $request->key)->firstOrFail();        
} catch (Illuminate\Database\Eloquent\ModelNotFoundException $e) {
    // Display error
}

对比

$user = User::where('identifier', $request->key)->first();
if (empty($user)) {
    // Display error
}

你不应该将密码保存为明文,你应该散列它。 Laravel 有一个 class 用于 hashing,您可以将其用作密码。当您创建新用户时,请执行以下操作:

$user = new User();
...
$user->password = Hash::make($request->get('newPassword'))
$user->save()

并检查凭据是否有效

public function login(Request $request)
{
    $email = $request->get('email');
    $password = $request->get('password');
    if (Auth::attempt(['email' => $email, 'password' => $password])) {
        // Authentication passed...
        return redirect()->intended('some place');
    }
}

有关 Authentication

的更详细的检查文档

编辑

对于原题,firstOrFail的思路是全局抛出一些错误,可以通过一些全局的方法来处理exception handler,如果不需要抛出全局错误,则使用find () 和 if 语句应该就是您所需要的。

至于你问题的 try/catch 部分,出于几个原因我会避免 try/catch。小的原因是 try/catch 在 PHP 中相当慢。主要原因是操作可能因 ModelNotFoundException 以外的其他原因而失败,并且您的代码将错过它。