PHP处理API不超过其限制?

时间:2012-10-27 18:34:59

标签: php api function caching oauth

我想知道如何不对API进行多次调用?例如,如果我正在尝试使用yelp的api,那么在超过之前它们会有一个限制的呼叫(一旦超过该数字,它们就会停止向您提供信息)。

我该怎么办?现在,我在每个页面中都有这个(来自他们的API PHP示例),我需要从他们的网站获取信息:

// For example, request business with id 'the-waterboy-sacramento'
//$unsigned_url = "http://api.yelp.com/v2/business/the-waterboy-sacramento";


// For examaple, search for 'tacos' in 'sf'
//$unsigned_url = "http://api.yelp.com/v2/search?term=tacos&location=sf";

// My own code
$unsigned_url = "http://api.yelp.com/v2/search?term=".$term."";
// $term is coming from searching

// Set your keys here
$consumer_key = "some_id";
$consumer_secret = "some_id";
$token = "some_id";
$token_secret = "some_id";

// Token object built using the OAuth library
$token = new OAuthToken($token, $token_secret);

// Consumer object built using the OAuth library
$consumer = new OAuthConsumer($consumer_key, $consumer_secret);

// Yelp uses HMAC SHA1 encoding
$signature_method = new OAuthSignatureMethod_HMAC_SHA1();

// Build OAuth Request using the OAuth PHP library. Uses the consumer and token object created above.
$oauthrequest = OAuthRequest::from_consumer_and_token($consumer, $token, 'GET', $unsigned_url);

// Sign the request
$oauthrequest->sign_request($signature_method, $consumer, $token);

// Get the signed URL
$signed_url = $oauthrequest->to_url();

// Send Yelp API Call
$ch = curl_init($signed_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch); // Yelp response
curl_close($ch);

当我想打电话给某个公司时,这在每个页面上做得过多。

2 个答案:

答案 0 :(得分:3)

我不使用它,但作为一般答案,考虑缓存数据库中的数据以减少API调用。它还可以提高您网站的性能,尤其是当需要API的相同数据的同一页面加载多次时。

这里基于文件的一般使用实施

/**
* Cache friendly function call stub.
* 
* @param callback $Callback
* @param array $Arguments
* @param integer $Expiration
* @return mixed
*/
function CallFunctionAndCacheResult($Callback, array $Arguments, $Expiration = 3600){
    // Validate $Callback
    if(!is_callable($Callback)){
        trigger_error('$Callback must be a callback.', E_USER_WARNING);
        return false;
    }
    // Validate $Arguments (we need some to hash)
    if(empty($Arguments)){
        trigger_error('$Arguments cannot be empty.', E_USER_WARNING);
        return false;
    }
    // Empty $Expiration means live calls
    if(empty($Expiration)){
        return call_user_func_array($Callback, $Arguments);
    }
    // Validate $Expiration (we need some to hash)
    if(!is_numeric($Expiration) or (($Expiration = intval($Expiration)) < 1)){
        trigger_error('$Expiration has to be a positive integer.', E_USER_WARNING);
        return false;
    }
    // Hash the Arguments (Unique Call ID)
    $Hash = md5(serialize($Arguments));
    // Check if Cache file exists
    if(is_file($Cache = dirname(__FILE__)."/{$Hash}.serial")){
        // Test if file expired
        if(($MTime = filemtime($Cache)) >= (time() - $Expiration)){
            // Attempt to load data, assume it's corrupted
            if(($Data = unserialize(file_get_contents($Cache))) !== false){
                return $Data;
            }
        }
    }
    // Now regenerate the data if you got here
    $Data = call_user_func_array($Callback, $Arguments);
    // Store it, with  LOCK_EX enabled to prevent collisions
    file_put_contents($Cache, serialize($Data), LOCK_EX);
    // Return the data
    return $Data;
}

// Test case (store current time for 10 seconds, keep refreshing)
var_dump($Data = CallFunctionAndCacheResult(function(){
    // Return some data to be cached
    return array_merge(func_get_args(), array(
        'cached'    => gmstrftime('%A, %d %B %Y %H:%M:%S'),
    ));
}, array(
    'Username',
    'Password',
    // ...
), 10));

希望它有意义。只需测试一下,弄明白并使用数据库引擎来达到相同的效果。

答案 1 :(得分:1)

缓存是你的朋友。如果您认为自己一遍又一遍地进行不需要的API查询,则应将信息缓存到cookie中,如果它的内容非常小/非关键,或者是数据库。

就像,如果用户希望刷新我运行查询以获取其名称的页面,我不想超出限制。您可以获取一次名称,将其存储到cookie中,然后使用它而不是每次查询。就像其他答案所说的那样,更快,更有效率。