### **將更新頻率極低且讀取幾率高的數據緩存為文件,獲取時不再查詢數據庫而是直接讀取和解析文件內容(適合新聞類網站)**
#### **將焦點圖查詢結果保存在 JSON 文件中,該文件存放于 public 文件夾目錄下,前端請求時,只要請求這個 JSON 文件即可,無需請求數據庫**
1. 首次查詢焦點圖
```
public function getBannerJson($num = 5)
{
$banner = Banner::where('status', 1)->limit($num)->order('id DESC')->select()->toJson();
return $banner;
}
```
2.將查詢結果保存在 JSON 文件中(下列代碼中,該文件存放路徑為 `public/json/banner.json`)
```
public function toJsonFile($json)
{
return file_put_contents($_SERVER['DOCUMENT_ROOT'] . '/json/banner.json', $json);
}
```
3.前端請求時,使用ajax進行請求,直接請求 JSON 文件
```
//首頁的輪播圖
$.ajax({
url: "/json/banner.json",
type: "get",
dataType: "json",
async: false,
success: function (json) {
if (json != null) {
console.log(json)
for (var i = 0; i < json.length; i++) {
$('.mainpage-slideshow-top .banner').append('<a href="' + json[i].url + '"><img src="' + json[i].url + '" alt="' + json[i].title + '"></a>');
}
}
},
error: function () {
console.log("AJAX fail");
}
});
```