使用缓存来避免速率限制是个好主意。 下面是一些示例代码,展示了我如何在Google+数据中使用它, 在最近编写的一些php代码中。
private function getCache($key) {
$cache_life = intval($this->instance['cache_life']); // minutes
if ($cache_life <= 0) return null;
// fully-qualified filename
$fqfname = $this->getCacheFileName($key);
if (file_exists($fqfname)) {
if (filemtime($fqfname) > (time() - 60 * $cache_life)) {
// The cache file is fresh.
$fresh = file_get_contents($fqfname);
$results = json_decode($fresh,true);
return $results;
}
else {
unlink($fqfname);
}
}
return null;
}
private function putCache($key, $results) {
$json = json_encode($results);
$fqfname = $this->getCacheFileName($key);
file_put_contents($fqfname, $json, LOCK_EX);
}
,并使用它:
// $cacheKey is a value that is unique to the
// concatenation of all params. A string concatenation
// might work.
$results = $this->getCache($cacheKey);
if (!$results) {
// cache miss; must call out
$results = $this->getDataFromService(....);
$this->putCache($cacheKey, $results);
}
最后一个似乎很简单,但我怎么会在我的网站上使用它。我对PHP还是比较陌生的,只是在过去的一年里一直在学习,所以原谅我的noobness。我不确定$ json =/*会像往常一样从twitter获取* /;部分。我是否像这样使用它: – GeordieDave1980 2012-07-10 06:36:35
我的代码: - 'code' $ query =“i%20hate%20my%20girlfriend”; $ query = urlencode($ query); $ url =“http://search.twitter.com/search.json?q={$query}&rpp=100&result_type=recent&lang=en”; $ tweet = file_get_contents($ url); $ tweet_array = json_decode($ tweet,true); foreach($ tweet_array ['results'] as $ data) { $ profileimg = $ data ['profile_image_url']; $ postfrom = $ data ['from_user_name']; $ postfromid = $ data ['from_user_id']; $ created = $ data ['created_at']; $ message = $ data ['text']; – GeordieDave1980 2012-07-10 06:44:15
我已经对我的代码留下了评论,我不确定如何将其放入评论框,希望您能够复制并粘贴它并将其分开,以便知道它的样子。我对这个函数做什么感到困惑。 – GeordieDave1980 2012-07-10 06:45:48