每次调用Auth类时,PHP的Laravel 4都会访问数据库吗?

时间:2013-08-30 19:54:47

标签: php laravel

我正在构建我的第一个Laravel 4应用程序(PHP)。

我发现自己需要在大多数模型和控制器中经常调用这样的东西......

$this->user = Auth::user();

所以我的问题是,在应用程序中多次调用它,多次访问数据库,或者它是否足够聪明,可以在其余的请求/页面构建中将其缓存到某个位置?

或者我需要自己做些什么?我浏览了Auth类但没有时间检查每个文件(16个文件用于Auth)

2 个答案:

答案 0 :(得分:9)

以下是方法Auth::user()的代码。

// vendor/laravel/framework/src/Illuminate/Auth/Guard.php

/**
 * Get the currently authenticated user.
 *
 * @return \Illuminate\Auth\UserInterface|null
 */
public function user()
{
    if ($this->loggedOut) return;

    // If we have already retrieved the user for the current request we can just
    // return it back immediately. We do not want to pull the user data every
    // request into the method becaue that would tremendously slow the app.
    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.
    $user = null;

    if ( ! is_null($id))
    {
        $user = $this->provider->retrieveByID($id);
    }

    // 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) and ! is_null($recaller))
    {
        $user = $this->provider->retrieveByID($recaller);
    }

    return $this->user = $user;
}

对我来说,看起来每次请求只会从数据库中获取一次用户。因此,您可以根据需要多次调用它。它只会打到DB一次。

答案 1 :(得分:1)

Auth::user()只能击中DB一次,所以这不是问题多次调用它。顺便说一句,您可以缓存您想要经常访问的用户的有用信息。