Laravel Selective Caching(Laravel 选择性缓存)
问题描述
我正在使用 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 选择性缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Laravel 选择性缓存
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- Laravel 仓库 2022-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- Mod使用GET变量将子域重写为PHP 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01