我正在使用 Laravel 4 框架开发我的第一个应用程序(顺便说一句,使用它进行设计是一种乐趣).对于一个组件,有一个 AJAX 请求来查询外部服务器.问题是,我想将这些响应缓存一段时间只有在它们成功时.
I'm developing one of my first applications with the Laravel 4 framework (which, by the way, is a joy to design with). For one component, there is an AJAX request to query an external server. The issue is, I want to cache these responses for a certain period of time only if they are successful.
Laravel 有 Cache::remember() 函数,但问题是似乎没有失败"模式(至少在他们的文档中没有描述)不会存储缓存.
Laravel has the Cache::remember() function, but the issue is there seems to be no "failed" mode (at least, none described in their documentation) where a cache would not be stored.
以这个简化函数为例:
try { $server->query(); } catch (Exception $e) { return Response::json('error', 400); }我想在这个输出上使用 Cache::remember,但是 只有 如果没有抛出异常.我可以想出一些不太优雅的方法来做到这一点,但我认为 Laravel 作为一个……雄辩的……框架,会有更好的方法.有什么帮助吗?谢谢!
I would like to use Cache::remember on the output of this, but only if no Exception was thrown. I can think of some less-than-elegant ways to do this, but I would think that Laravel, being such an... eloquent... framework, would have a better way. Any help? Thanks!
推荐答案这对我有用:
if (Cache::has($key)) { $data = Cache::get($key); } else { try { $data = longQueryOrProcess($key); Cache::forever($key, $data); // only stored when no error } catch (Exception $e) { // deal with error, nothing cached } }当然你也可以使用 Cache::put($key, $data, $minutes); 而不是 forever
And of course you could use Cache::put($key, $data, $minutes); instead of forever
更多推荐
Laravel 选择性缓存
发布评论