4

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

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

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

所以我的问题是,是在应用程序中多次调用它,多次访问数据库,还是足够聪明地在请求/页面构建的其余部分缓存它?

还是我需要自己做不同的事情?我浏览了 Auth 类,但没有时间检查每个文件(16 个文件用于 Auth)

4

2 回答 2

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;
}

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

于 2013-08-30T20:29:00.487 回答
1

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

于 2013-08-30T21:34:24.697 回答