Laravel Auth::check()是否总是连接到数据库来检查用户



我正在使用Auth::check()检查用户的登录状态。

Auth::check()是否连接到数据库以执行每次登录检查?

Auth::check()验证当前会话是否有经过身份验证的用户,无论是已经验证的,还是来自会话(将首次使用DB(或null。

Illuminate\Auth\GuardHelpers.php

**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return ! is_null($this->user());
}

示例@Illuminate\Auth\RequestGuard.php

/**
* Get the currently authenticated user.
*
* @return IlluminateContractsAuthAuthenticatable|null
*/
public function user()
{
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
return $this->user = call_user_func(
$this->callback, $this->request, $this->getProvider()
);
}

默认保护不是RequestGuard,而是SessionGuard。是的,第一次调用Auth::check()时,它将执行一次数据库查找,以检查当前登录的用户。

之后,同一请求中的每个连续调用都不会执行另一个数据库查找。

check()方法执行以下操作:

/**
* Determine if the current user is authenticated.
*
* @return bool
*/
public function check()
{
return ! is_null($this->user());
}

现在,有趣的部分是user()方法的作用。你可以在源代码中看到详细的解释

public function user()
{
if ($this->loggedOut) {
return;
}
// If we've already retrieved the user for the current request we can just
// return it back immediately. We do not want to fetch the user data on
// every call to this method because that would be tremendously slow.
if (! is_null($this->user)) {
return $this->user;
}
$id = $this->session->get($this->getName());
// First we will try to load the user using the identifier in the session if
// one exists. Otherwise we will check for a "remember me" cookie in this
// request, and if one exists, attempt to retrieve the user using that.
if (! is_null($id) && $this->user = $this->provider->retrieveById($id)) {
$this->fireAuthenticatedEvent($this->user);
}
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
if (is_null($this->user) && ! is_null($recaller = $this->recaller())) {
$this->user = $this->userFromRecaller($recaller);
if ($this->user) {
$this->updateSession($this->user->getAuthIdentifier());
$this->fireLoginEvent($this->user, true);
}
}
return $this->user;
}

最新更新