Пакетные вызовы с помощью Facebook Graph API и PHP

Проектирование моего первого приложения против Graph API, используя версию 2.1.2 библиотеки PHP, предоставленной Facebook. Пытаясь максимизировать производительность и т. Д. Из коробки и вы хотите объединить несколько звонков в один звонок, но не можете найти что-либо в документации … Я уверен, что мне не хватает чего-то простого, но я в тупике.

Я хотел бы включить эти вызовы (только пример) в один пакетный вызов:

$me = $facebook->api('/me', $params); $groups = $facebook->api('/me/groups', $params); 

Facebook рекомендует использовать FQL для этого; http://developers.facebook.com/docs/guides/performance , объединив ваши запросы в (вложенном) запросе.

Их собственный пример:

 $friends_locations = $facebook->api_client->fql_query( 'SELECT hometown_location from user where uid in ' . '(SELECT uid2 from friend where uid1=' . $user_id . ')'); 

Если ваши запросы не зависят от eachother, вы можете использовать fql.multiquery

Просто обновление для нового пакета Batch API: вы также можете выполнить его следующим образом:

 // Save your method calls into an array $queries = array( array('method' => 'GET', 'relative_url' => '/me'), array('method' => 'GET', 'relative_url' => '/me/groups') ); // POST your queries to the batch endpoint on the graph. $batchResponse = $facebook->api('?batch='.json_encode($queries), 'POST'); // Return values are indexed in order of the original array, content is in ['body'] as a JSON // string. Decode for use as a PHP array. $user_profile = json_decode($batchResponse[0]['body'], true); $user_groups = json_decode($batchResponse[1]['body'], true); 

Это должно делать свое дело.

Я привел пример для пакетных вызовов запросов fql. Это может помочь кому-то.

// $ current_user = facebook id

  $query1="SELECT uid, name FROM user WHERE is_app_user=1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = $current_user)"; $query2="SELECT uid, name, work_history FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = $current_user )"; $query3="SELECT uid, name, work, education FROM user WHERE uid = $current_user"; $queries = array( array('method'=>'GET', 'relative_url'=>'method/fql.query?query='.str_replace(' ','+',$query1)), array('method'=>'GET', 'relative_url'=>'method/fql.query?query='.str_replace(' ','+',$query2)), array('method'=>'GET', 'relative_url'=>'method/fql.query?query='.str_replace(' ','+',$query3)) ); $objs = $facebook->api('/?batch='.json_encode($queries), 'POST'); 

$ objs получает массив json из целого результата запросов.

И это экономит время много. Эти 3 запроса индивидуально занимают 9 секунд. С мультикрой это занимает 7 секунд. И с пакетным запросом он занимает 3,6 секунды.

Я добавил нулевую проверку:

 $friends_locations = $facebook->api_client->fql_query('SELECT name,birthday_date, pic_square FROM user WHERE uid in (SELECT uid2 from friend where uid1='. $user_id .') and birthday_date > 0'); 

Для Batch API вы можете использовать класс Batch для Facebook .

Вот код, который вы использовали бы :

 <?php // Facebook Batch Requests PHP Class // by Gokhan Ozturk <gokhanozturk at gmail dot com> @ Nov 17, 2011 // Original Article: http://blog.pclabs.com.tr/gokhanozturk/2011/11/17/facebook-batch-requests-php-class/ class facebook_batch { protected $requests = array(); protected $responses = null; protected $cur = 1; protected $map = array(); const MAX_NUMBER_OF_REQUESTS = 20; public function add($path, $method = 'GET', $params = array(), $extra = array()) { if(count($this->requests) > self::MAX_NUMBER_OF_REQUESTS) return false; $path = trim($path, '/ '); $body = http_build_query($params); $body = urldecode($body); if(strtolower($method) == 'get') { if(count($params) > 0) { $path .= "?" . $body; $body = ""; } } $key = $this->cur++; $this->requests[$key] = array_merge(array('relative_url' => $path, 'method' => $method, 'body' => $body), $extra); return intval($key); } public function remove($key) { unset($this->requests[$key]); } public function execute() { global $facebook; $i = 0; foreach($this->requests as $k => $r) { $this->map[$k] = $i++; } $batch = json_encode(array_values($this->requests)); $params = array('batch' => $batch); $this->responses = $facebook->api('/', 'POST', $params); } public function response($key) { if(! $this->responses) $this->execute(); $rkey = $this->map[intval($key)]; $resp = $this->responses[intval($rkey)]; if($resp['code'] != 200) return false; return json_decode($resp['body'], true); } public function getRequests() { return $this->requests; } } ?> не <?php // Facebook Batch Requests PHP Class // by Gokhan Ozturk <gokhanozturk at gmail dot com> @ Nov 17, 2011 // Original Article: http://blog.pclabs.com.tr/gokhanozturk/2011/11/17/facebook-batch-requests-php-class/ class facebook_batch { protected $requests = array(); protected $responses = null; protected $cur = 1; protected $map = array(); const MAX_NUMBER_OF_REQUESTS = 20; public function add($path, $method = 'GET', $params = array(), $extra = array()) { if(count($this->requests) > self::MAX_NUMBER_OF_REQUESTS) return false; $path = trim($path, '/ '); $body = http_build_query($params); $body = urldecode($body); if(strtolower($method) == 'get') { if(count($params) > 0) { $path .= "?" . $body; $body = ""; } } $key = $this->cur++; $this->requests[$key] = array_merge(array('relative_url' => $path, 'method' => $method, 'body' => $body), $extra); return intval($key); } public function remove($key) { unset($this->requests[$key]); } public function execute() { global $facebook; $i = 0; foreach($this->requests as $k => $r) { $this->map[$k] = $i++; } $batch = json_encode(array_values($this->requests)); $params = array('batch' => $batch); $this->responses = $facebook->api('/', 'POST', $params); } public function response($key) { if(! $this->responses) $this->execute(); $rkey = $this->map[intval($key)]; $resp = $this->responses[intval($rkey)]; if($resp['code'] != 200) return false; return json_decode($resp['body'], true); } public function getRequests() { return $this->requests; } } ?>