vlechemin/facebook-batch-api

使用Facebook SDK通过批量请求,无需在预处理和后处理阶段使代码复杂化。

v1.0.0 2013-04-09 18:42 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:03:33 UTC


README

目标是使用Facebook SDK通过批量请求,无需在预处理和后处理阶段使代码复杂化。

技巧是使用引用返回一个临时占位符,并在需要时用实际结果替换该占位符。

用法

// use the api as usual, please note the &
$me = &$facebook->batchApi('/me');
$picture = &$facebook->batchApi('/me/picture', 'GET', [
    'type' => 'large',
    'return_ssl_resources' => 1,
]);

// execute the batch to fill $me and $picture with the real value
$facebook->processBatch();

// use the results
var_dump($me);
var_dump($picture);

包含多个方法的批量请求

curl \
    -F 'access_token=…' \
    -F 'batch=[{ "method":"POST","relative_url":"me/feed","body":"message=Test status update&link=https://developers.facebook.com/"},{ "method":"GET","relative_url":"me/feed?limit=1"}]' \
    https://graph.facebook.com

第二个参数使得方法之间的交替变得简单。

$result1 = &$facebook->batchApi('me/feed', 'POST', [
    'message' => 'Test status update',
    'link' => 'https://developers.facebook.com/',
]);
$result2 = &$facebook->batchApi('me/feed', 'GET', [
    'limit' => 1,
]);
$facebook->processBatch();

在请求中指定操作之间的依赖关系

curl \
   -F 'access_token=...' \
   -F 'batch=[{ "method":"GET","name":"get-friends","relative_url":"me/friends?limit=5",},{"method":"GET","relative_url":"?ids={result=get-friends:$.data.*.id}"}]' \
   https://graph.facebook.com/

批量请求可以用第四个参数命名,以便后续使用。

$result1 = &$facebook->batchApi('me/friends', 'GET', [
    'limit' => 5,
], [
    'name' => 'get-friends',
]);
$result2 = &$facebook->batchApi('/', 'GET', [
    'ids' => '{result=get-friends:$.data.*.id}',
]);
$facebook->processBatch();

上传二进制数据

curl 
     -F 'access_token=…' \
     -F 'batch=[{"method":"POST","relative_url":"me/photos","body":"message=My cat photo","attached_files":"file1"},{"method":"POST","relative_url":"me/photos","body":"message=My dog photo","attached_files":"file2"},]' \
     -F 'file1=@cat.gif' \
     -F 'file2=@dog.jpg' \
    https://graph.facebook.com

可以使用 attachFile 方法来附加文件。文件名和批量参数之间的对应关系是在内部实现的。

$result1 = &$facebook->batchApi('me/photos', 'POST', [
    'message' => 'My cat photo',
], [
    'attached_files' => $facebook->attachFile('@cat.gif'),
]);
$result2 = &$facebook->batchApi('me/photos', 'POST', [
    'message' => 'My dog photo',
], [
    'attached_files' => $facebook->attachFile('@dog.jpg'),
]);
$facebook->processBatch();