我正在构建我的第一个Laravel 4应用程序(PHP)。
我发现自己需要在我的大多数模型和控制器中经常调用这样的东西。。。
$this->user = Auth::user();
所以我的问题是,是在应用程序中多次调用它,多次访问数据库,还是它足够聪明,可以在请求/页面构建的剩余时间将其缓存在某个地方?
还是我需要自己做不同的事情?我浏览了一下Auth类,但没有时间检查每个文件(Auth有16个文件)
这是方法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一次。
Auth::user()
只访问DB一次,所以多次调用它不是问题。顺便说一句,你可以缓存你想经常访问的用户的有用信息。