Skip to content
This repository was archived by the owner on Jan 13, 2022. It is now read-only.

Commit ecab68b

Browse files
authored
Merge pull request #713 from teldosas/full-batch-v5.4
Add full batch support without BC breaks
2 parents d9b7427 + 4980f3a commit ecab68b

File tree

7 files changed

+343
-75
lines changed

7 files changed

+343
-75
lines changed

docs/examples/batch_request.md

Lines changed: 183 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,12 @@ This example covers sending a batch request with the Facebook SDK for PHP.
77
The following example assumes we have the following permissions granted from the user: `user_likes`, `user_events`, `user_photos`, `publish_actions`. The example makes use of [JSONPath to reference specific batch operations](https://developers.facebook.com/docs/graph-api/making-multiple-requests/#operations).
88

99
```php
10+
<?php
1011
$fb = new Facebook\Facebook([
11-
'app_id' => '{app-id}',
12-
'app_secret' => '{app-secret}',
13-
'default_graph_version' => 'v2.8',
14-
]);
12+
'app_id' => '{app-id}',
13+
'app_secret' => '{app-secret}',
14+
'default_graph_version' => 'v2.8',
15+
]);
1516

1617
// Since all the requests will be sent on behalf of the same user,
1718
// we'll set the default fallback access token here.
@@ -51,29 +52,30 @@ $batch = [
5152
echo '<h1>Make a batch request</h1>' . "\n\n";
5253

5354
try {
54-
$responses = $fb->sendBatchRequest($batch);
55-
} catch(Facebook\Exceptions\FacebookResponseException $e) {
56-
// When Graph returns an error
57-
echo 'Graph returned an error: ' . $e->getMessage();
58-
exit;
59-
} catch(Facebook\Exceptions\FacebookSDKException $e) {
60-
// When validation fails or other local issues
61-
echo 'Facebook SDK returned an error: ' . $e->getMessage();
62-
exit;
55+
$responses = $fb->sendBatchRequest($batch);
56+
} catch (Facebook\Exceptions\FacebookResponseException $e) {
57+
// When Graph returns an error
58+
echo 'Graph returned an error: ' . $e->getMessage();
59+
exit;
60+
} catch (Facebook\Exceptions\FacebookSDKException $e) {
61+
// When validation fails or other local issues
62+
echo 'Facebook SDK returned an error: ' . $e->getMessage();
63+
exit;
6364
}
6465

6566
foreach ($responses as $key => $response) {
66-
if ($response->isError()) {
67-
$e = $response->getThrownException();
68-
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
69-
echo '<p>Graph Said: ' . "\n\n";
70-
var_dump($e->getResponse());
71-
} else {
72-
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
73-
echo "Response: " . $response->getBody() . "</p>\n\n";
74-
echo "<hr />\n\n";
75-
}
67+
if ($response->isError()) {
68+
$e = $response->getThrownException();
69+
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
70+
echo '<p>Graph Said: ' . "\n\n";
71+
var_dump($e->getResponse());
72+
} else {
73+
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
74+
echo "Response: " . $response->getBody() . "</p>\n\n";
75+
echo "<hr />\n\n";
76+
}
7677
}
78+
7779
```
7880

7981
There five requests being made in this batch requests.
@@ -96,48 +98,181 @@ My next 2 events are House Warming Party,Some Foo Event.
9698

9799
It should also contain a response containing two photos from the user.
98100

99-
> **Warning:** The response object should return a `null` response for any request that was pointed to with JSONPath as is [the behaviour of the batch functionality of the Graph API](https://developers.facebook.com/docs/graph-api/making-multiple-requests/#operations).
101+
> **Warning:** The response object should return a `null` response for any request that was pointed to with JSONPath as is [the behaviour of the batch functionality of the Graph API](https://developers.facebook.com/docs/graph-api/making-multiple-requests/#operations). If we want to receive the response anyway we have to set the `omit_response_on_success` option to `false`. [See the example below](#force-response-example).
102+
103+
## Force Response Example
104+
105+
The following example is a subset of the [first example](#example). We will only use the `user-events` and `post-to-feed` requests of the [first example](#example), but in this case we will force the server to return the response of the `user-events` request.
106+
107+
```php
108+
<?php
109+
$fb = new Facebook\Facebook([
110+
'app_id' => '{app-id}',
111+
'app_secret' => '{app-secret}',
112+
'default_graph_version' => 'v2.8',
113+
]);
114+
115+
// Since all the requests will be sent on behalf of the same user,
116+
// we'll set the default fallback access token here.
117+
$fb->setDefaultAccessToken('user-access-token');
118+
119+
// Get user events
120+
$requestUserEvents = $fb->request('GET', '/me/events?fields=id,name&limit=2');
121+
122+
// Post a status update with reference to the user's events
123+
$message = 'My next 2 events are {result=user-events:$.data.*.name}.';
124+
$statusUpdate = ['message' => $message];
125+
$requestPostToFeed = $fb->request('POST', '/me/feed', $statusUpdate);
126+
127+
// Create an empty batch request
128+
$batch = $fb->newBatchRequest();
129+
130+
// Populate the batch request
131+
// Set the 'omit_response_on_success' option to false to force the server return the response
132+
$batch->add($requestUserEvents, [
133+
"name" => "user-events",
134+
"omit_response_on_success" => false
135+
]);
136+
$batch->add($requestPostToFeed, "post-to-feed");
137+
138+
// Send the batch request
139+
try {
140+
$responses = $fb->getClient()->sendBatchRequest($batch);
141+
} catch (Facebook\Exceptions\FacebookResponseException $e) {
142+
// When Graph returns an error
143+
echo 'Graph returned an error: ' . $e->getMessage();
144+
exit;
145+
} catch (Facebook\Exceptions\FacebookSDKException $e) {
146+
// When validation fails or other local issues
147+
echo 'Facebook SDK returned an error: ' . $e->getMessage();
148+
exit;
149+
}
150+
151+
foreach ($responses as $key => $response) {
152+
if ($response->isError()) {
153+
$e = $response->getThrownException();
154+
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
155+
echo '<p>Graph Said: ' . "\n\n";
156+
var_dump($e->getResponse());
157+
} else {
158+
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
159+
echo "Response: " . $response->getBody() . "</p>\n\n";
160+
echo "<hr />\n\n";
161+
}
162+
}
163+
164+
```
165+
166+
## Explicit Dependency Example
167+
168+
In the following example we will make two requests.
169+
* One to post a status update on the user's feed
170+
* and one to receive the last post of the user (which should be the one that we posted with first request).
171+
172+
Since we want the second request to be executed after the first one is completed, we have to set the `depends_on` option of the second request to point to the name of the first request. We assume that we have the following options granted from the user: `user_posts`, `publish_actions`.
173+
174+
```php
175+
<?php
176+
$fb = new Facebook\Facebook([
177+
'app_id' => '{app-id}',
178+
'app_secret' => '{app-secret}',
179+
'default_graph_version' => 'v2.8',
180+
]);
181+
182+
// Since all the requests will be sent on behalf of the same user,
183+
// we'll set the default fallback access token here.
184+
$fb->setDefaultAccessToken('user-access-token');
185+
186+
// Post a status update to the user's feed
187+
$message = 'Random status update';
188+
$statusUpdate = ['message' => $message];
189+
$requestPostToFeed = $fb->request('POST', '/me/feed', $statusUpdate);
190+
191+
// Get last post of the user
192+
$requestLastPost = $fb->request('GET', '/me/feed?limit=1');
193+
194+
// Create an empty batch request
195+
$batch = $fb->newBatchRequest();
196+
197+
// Populate the batch request
198+
$batch->add($requestPostToFeed, "post-to-feed");
199+
200+
// Set the 'depends_on' property to point to the first request
201+
$batch->add($requestLastPost, [
202+
"name" => "last-post",
203+
"depends_on" => "post-to-feed"
204+
]);
205+
206+
// Send the batch request
207+
try {
208+
$responses = $fb->getClient()->sendBatchRequest($batch);
209+
} catch (Facebook\Exceptions\FacebookResponseException $e) {
210+
// When Graph returns an error
211+
echo 'Graph returned an error: ' . $e->getMessage();
212+
exit;
213+
} catch (Facebook\Exceptions\FacebookSDKException $e) {
214+
// When validation fails or other local issues
215+
echo 'Facebook SDK returned an error: ' . $e->getMessage();
216+
exit;
217+
}
218+
219+
foreach ($responses as $key => $response) {
220+
if ($response->isError()) {
221+
$e = $response->getThrownException();
222+
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
223+
echo '<p>Graph Said: ' . "\n\n";
224+
var_dump($e->getResponse());
225+
} else {
226+
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
227+
echo "Response: " . $response->getBody() . "</p>\n\n";
228+
echo "<hr />\n\n";
229+
}
230+
}
231+
```
232+
233+
> **Warning:** The response object should return a `null` response for any request that was pointed to with the `depends_on` option as is [the behaviour of the batch functionality of the Graph API](https://developers.facebook.com/docs/graph-api/making-multiple-requests/#operations). If we want to receive the response anyway we have to set the `omit_response_on_success` option to `false`. [See example](#force-response-example).
100234
101235
## Multiple User Example
102236

103237
Since the requests sent in a batch are unrelated by default, we can make requests on behalf of multiple users and pages in the same batch request.
104238

105239
```php
240+
<?php
106241
$fb = new Facebook\Facebook([
107-
'app_id' => '{app-id}',
108-
'app_secret' => '{app-secret}',
109-
'default_graph_version' => 'v2.8',
110-
]);
242+
'app_id' => '{app-id}',
243+
'app_secret' => '{app-secret}',
244+
'default_graph_version' => 'v2.8',
245+
]);
111246

112247
$batch = [
113248
$fb->request('GET', '/me?fields=id,name', 'user-access-token-one'),
114249
$fb->request('GET', '/me?fields=id,name', 'user-access-token-two'),
115250
$fb->request('GET', '/me?fields=id,name', 'page-access-token-one'),
116251
$fb->request('GET', '/me?fields=id,name', 'page-access-token-two'),
117-
];
252+
];
118253

119254
try {
120-
$responses = $fb->sendBatchRequest($batch);
121-
} catch(Facebook\Exceptions\FacebookResponseException $e) {
122-
// When Graph returns an error
123-
echo 'Graph returned an error: ' . $e->getMessage();
124-
exit;
125-
} catch(Facebook\Exceptions\FacebookSDKException $e) {
126-
// When validation fails or other local issues
127-
echo 'Facebook SDK returned an error: ' . $e->getMessage();
128-
exit;
255+
$responses = $fb->sendBatchRequest($batch);
256+
} catch (Facebook\Exceptions\FacebookResponseException $e) {
257+
// When Graph returns an error
258+
echo 'Graph returned an error: ' . $e->getMessage();
259+
exit;
260+
} catch (Facebook\Exceptions\FacebookSDKException $e) {
261+
// When validation fails or other local issues
262+
echo 'Facebook SDK returned an error: ' . $e->getMessage();
263+
exit;
129264
}
130265

131266
foreach ($responses as $key => $response) {
132-
if ($response->isError()) {
133-
$e = $response->getThrownException();
134-
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
135-
echo '<p>Graph Said: ' . "\n\n";
136-
var_dump($e->getResponse());
137-
} else {
138-
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
139-
echo "Response: " . $response->getBody() . "</p>\n\n";
140-
echo "<hr />\n\n";
141-
}
267+
if ($response->isError()) {
268+
$e = $response->getThrownException();
269+
echo '<p>Error! Facebook SDK Said: ' . $e->getMessage() . "\n\n";
270+
echo '<p>Graph Said: ' . "\n\n";
271+
var_dump($e->getResponse());
272+
} else {
273+
echo "<p>(" . $key . ") HTTP status code: " . $response->getHttpStatusCode() . "<br />\n";
274+
echo "Response: " . $response->getBody() . "</p>\n\n";
275+
echo "<hr />\n\n";
276+
}
142277
}
143278
```

docs/reference/Facebook.md

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,23 @@ $batchResponse = $fb->sendBatchRequest($requests);
349349

350350
[See a full batch example](../examples/batch_request.md).
351351

352+
## newBatchRequest()
353+
```php
354+
public Facebook\FacebookBatchRequest newBatchRequest(
355+
string|AccessToken|null $accessToken,
356+
string|null $graphVersion
357+
)
358+
```
359+
360+
Instantiates an empty `Facebook\FacebookBatchRequest`.
361+
To populate it use the [`Facebook\FacebookBatchRequest::add()`](FacebookBatchRequest.md#add) method.
362+
363+
The `$accessToken` and `$graphVersion` arguments are the same as `get()` above.
364+
If any of the requests contained in the batch request does not have either the `$accessToken` or the `$graphVersion` set,
365+
it fallbacks to the values provided in the instantiation of the batch request.
366+
367+
[See a full batch example](../examples/batch_request.md).
368+
352369
## getRedirectLoginHelper()
353370
```php
354371
public Facebook\Helpers\FacebookRedirectLoginHelper getRedirectLoginHelper()

docs/reference/FacebookBatchRequest.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ Represents a batch request that will be sent to the Graph API.
44

55
## Facebook\FacebookBatchRequest
66

7-
You can instantiate a new `FacebookBatchRequest` entity directly by sending the arguments to the constructor.
7+
You can instantiate a new `FacebookBatchRequest` entity directly by sending the arguments to the constructor or
8+
by using the [`Facebook\Facebook::newBatchRequest()`](Facebook.md#newBatchRequest) factory method.
89

910
```php
1011
use Facebook\FacebookBatchRequest;
@@ -61,9 +62,9 @@ Since the `Facebook\FacebookBatchRequest` is extended from the [`Facebook\Facebo
6162
### add()
6263
```php
6364
public add(
64-
array|Facebook\FacebookBatchRequest $request,
65-
string|null $name
66-
)
65+
array|Facebook\FacebookBatchRequest $request,
66+
string|null $name
67+
)
6768
```
6869
Adds a request to be sent in the batch request. The `$request` can be a single [`Facebook\FacebookRequest`](FacebookRequest.md) or an array of `Facebook\FacebookRequest`'s.
6970

src/Facebook/Facebook.php

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,27 @@ public function sendBatchRequest(array $requests, $accessToken = null, $graphVer
494494
return $this->lastResponse = $this->client->sendBatchRequest($batchRequest);
495495
}
496496

497+
/**
498+
* Instantiates an empty FacebookBatchRequest entity.
499+
*
500+
* @param AccessToken|string|null $accessToken The top-level access token. Requests with no access token
501+
* will fallback to this.
502+
* @param string|null $graphVersion The Graph API version to use.
503+
* @return FacebookBatchRequest
504+
*/
505+
public function newBatchRequest($accessToken = null, $graphVersion = null)
506+
{
507+
$accessToken = $accessToken ?: $this->defaultAccessToken;
508+
$graphVersion = $graphVersion ?: $this->defaultGraphVersion;
509+
510+
return new FacebookBatchRequest(
511+
$this->app,
512+
[],
513+
$accessToken,
514+
$graphVersion
515+
);
516+
}
517+
497518
/**
498519
* Instantiates a new FacebookRequest entity.
499520
*

0 commit comments

Comments
 (0)