Laravel Auth :: check()是否始终连接到数据库以检查用户?

问题描述 投票:0回答:3

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

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

laravel
3个回答
0
投票

[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 \Illuminate\Contracts\Auth\Authenticatable|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()
        );
    }

0
投票

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

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


-1
投票

check()方法执行此操作:

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

现在,有趣的部分是user()方法的作用。您可以查看它的详细信息并进行很好的解释in the source code

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;
}
© www.soinside.com 2019 - 2024. All rights reserved.