我正在构建我的第一个Laravel 4应用程序(PHP).
我发现自己需要在大多数模型和控制器中经常调用这样的东西......
$this->user = Auth::user();
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,在应用程序中多次调用它,多次访问数据库,或者它是否足够智能,可以在其余的请求/页面构建中缓存它?
或者我需要自己做不同的事情吗?我浏览了Auth类,但没有时间检查每个文件(16个文件用于Auth)
这是方法的代码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;
}
Run Code Online (Sandbox Code Playgroud)
对我来说,看起来每次请求只会从数据库中获取一次用户.因此,您可以根据需要多次调用它.它只会击中DB一次.
| 归档时间: |
|
| 查看次数: |
731 次 |
| 最近记录: |