2013-08-30 36 views
4

我建立我的第一個Laravel 4應用程序(PHP)。每次調用Auth類時,PHP的Laravel 4是否都會訪問數據庫?

我覺得自己需要調用的財產以後這樣經常在我的大多數模型和控制器的...

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

所以我的問題是,呼籲在應用了幾次,命中數據庫幾次,還是它足夠聰明,可以將其緩存在剩餘的請求/頁面構建中?

或者我需要做不同的自己?我瀏覽了驗證類但沒有時間去檢查每個文件(16個文件進行驗證)

回答

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

Auth::user()只打一次DB,所以它不是一個問題,調用了很多次。順便說一句,你可以緩存你想經常訪問的用戶的有用信息。

相關問題