2016-09-28 75 views
5

Laravel文檔舉這個例子:如何通過變量來緩存::記憶功能

$value = Cache::remember('users', $minutes, function() { 
    return DB::table('users')->get(); 
}); 

在我來說,我有

public function thumb($hash, $extension) 
{ 
    Cache::remember('thumb-'.$hash, 15, function() { 
     $image = Image::where('hash', $hash)->first(); 
    }); 

如果我跑,我得到ErrorException in ImageController.php line 69: Undefined variable: hash。我試圖通過$哈希函數,像這樣:

Cache::remember('thumb-'.$hash, 15, function($hash) 

但隨後得到了另一個錯誤如下:

缺少參數1爲App \ HTTP \控制器\ ImageController ::應用程序\ HTTP \控制器{閉合}(),被稱爲在C:\ XAMPP \ htdocs中\ imagesharing \廠商\ laravel \框架\ SRC \照亮\緩存\ Repository.php上線316和限定

如何傳遞參數,所以我可以在我的查詢中使用它?

回答

12

你需要通過它使用use

Cache::remember('thumb-'.$hash, 15, function() use ($hash) { 
    $image = Image::where('hash', $hash)->first(); 
}); 
+1

要添加更多的細節 - 這不是一個laravel問題,這是關閉/匿名函數如何在PHP中工作。請參閱[PHP文檔](http://php.net/manual/en/functions.anonymous.php) –

+0

謝謝,那個竅門 –

+0

我決定永遠使用而不是記住,而這個Cache :: forever(' thumb - '。$ hash,function()use($ hash)給我在FileStore.php中的異常第102行:不允許使用'Closure'序列化,是不是可以永遠使用閉包? –