我正在实施一些来自Instagram的照片,用于我的页脚作为我的laravel项目中的装饰。但是当我刷新页面时,它会一遍又一遍地进行api调用。我正在考虑在会话中缓存或存储呼叫,因此我不必总是发送API请求...那么如何缓存此api请求?
PHP:
<?php
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = json_decode(curl_exec($curl));
?>
HTML:
<footer>
<?php
echo "<ul class='inline-list'>";
foreach ($results->data as $result) {
echo "<li><img src='".$result->images->thumbnail->url."'></li>";
}
echo "</ul>";
?>
</footer>
答案 0 :(得分:3)
要缓存请求,您可以将其写入文件并检查修改日期或使用某种缓存库。
例如http://www.phpfastcache.com/
// In your config file
include("phpfastcache/phpfastcache.php");
phpFastCache::setup("storage","auto");
// phpFastCache support "apc", "memcache", "memcached", "wincache" ,"files", "sqlite" and "xcache"
// You don't need to change your code when you change your caching system. Or simple keep it auto
$cache = phpFastCache();
// In your Class, Functions, PHP Pages
// try to get from Cache first. product_page = YOUR Identity Keyword
$results = $cache->get("cache_instagram");
if($results == null) {
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = json_decode(curl_exec($curl));
// set products in to cache in 600 seconds = 10 minutes
$cache->set("cache_instagram", $results,600);
}
// Output Your Contents $products HERE
// Re-written first example from page for purpouse of your script.
对于Laravel内置缓存
// http://laravel.com/docs/4.2/cache
if (Cache::has('cache_instagram')) {
$results = Cache::get('cache_instagram');
} else {
$clientid = "XXXXXXXXXXXXXXXXXXXXXXXX";
$url = "https://api.instagram.com/v1/tags/kittens/media/recent?client_id=".$clientid;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
$results = curl_exec($curl);
Cache::put('cache_instagram', $results, 60); // 1 hour
}
$results = json_decode($results);