默认的auth中间件做用户认证,每次都会查询数据库吗?


想了解一下laravel默认的认证流程,查看了源码,auth.php中默认的guard是web,查看它的配置,driver为session,provider是App\User eloquent,于是猜想,第一次登录认证应该是通过provider查数据库,并将用户信息放入session,之后的请求都是从session获得用户信息,如果session中没有就说明没有登录.
为了验证我的猜想,继续查看源码,中间件中的认证是在
Illuminate\Auth\Middleware\Authenticate

$this->auth->authenticate()
这一句,其中auth默认是
Illuminate\Auth\AuthManager
,它的authenticate()方法是用的__call,实际调用的是SessionGuard中的authenticate(),这其中主要的认证就是下面的代码:
`
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());//从session中获取用户id

    // 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.
    $user = null;

    if (! is_null($id)) {
        if ($user = $this->provider->retrieveById($id)) {//从数据库获取用户
            $this->fireAuthenticatedEvent($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.
    $recaller = $this->getRecaller();

    if (is_null($user) && ! is_null($recaller)) {
        $user = $this->getUserByRecaller($recaller);

        if ($user) {
            $this->updateSession($user->getAuthIdentifier());

            $this->fireLoginEvent($user, true);
        }
    }

    return $this->user = $user;
}

`
从上面代码可以看出来,其实session中存的只是user表的id,如果我想获得用户的信息,每次用Auth::user()的使用,其实都是走数据库的.

以上是我的分析,不知道对不对,如果是这样,性能会不会很差啊?


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: 后台生成复选框checkbox问题,选中1个变全选

>> 下一篇: 发送邮件问题