how to cache the twitter api result?

十年热恋 提交于 2019-12-31 09:07:56

问题


I would like to cache the result of the twitter api result and display them to users..

What's the best method to cache the result?

I'm thinking a writing the result into a file based on a time limit.. Is that ok or any other method should be used?

And most importantly what would be the ideal cache time ? I would like to display the latest content from the twitter but the twitter api has the request limits.. And my site has solid visitors/day..


回答1:


The cleanest way to do this would be to use APC (Alternative PHP Cache) if it installed. This has a built in "time to live" functionality:

if (apc_exists('twitter_result')) {
    $twitter_result = apc_fetch('twitter_result');
} else {
    $twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is
    apc_store('twitter_result', $twitter_result, 10 * 60); // store for 10 mins
}

A 10 minute timeout on the data would be my choice. This would vary depending on how frequently the feed is updated...


Edit If you don't have APC installed, you could do this using a very simple file:

if (file_exists('twitter_result.data')) {
    $data = unserialize(file_get_contents('twitter_result.data'));
    if ($data['timestamp'] > time() - 10 * 60) {
        $twitter_result = $data['twitter_result'];
    }
}

if (!$twitter_result) { // cache doesn't exist or is older than 10 mins
    $twitter_result = file_get_contents('http://twitter.com/...'); // or whatever your API call is

    $data = array ('twitter_result' => $twitter_result, 'timestamp' => time());
    file_put_contents('twitter_result.data', serialize($data));
}


来源:https://stackoverflow.com/questions/4123823/how-to-cache-the-twitter-api-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!