2016-09-28 78 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'序列化,是不是可以永远使用闭包? –