I’m trying to make use of Guzzle to send two POST requests one after another (first to create a user, then to assign them a segment) and I seem to be struggling with accessing the variables I’ve defined throughout.
I’ve got the following in my function:
$data = [
'email' => $email,
];
if (!empty($name)) {
$data['fname'] = $name;
}
$request = $api->postAsync('v1/subscribers', [
'auth' => [$account_data['api_key'], ''],
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'first_name' => $data['fname'] ?? '',
'email' => $data['email'],
]),
]);
$request->then(
function (ResponseInterface $res) {
$api->post('v1/subscribers/' . $data['email'] . '/segments', [
'auth' => [$account_data['api_key'], ''],
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'segment_ids' => [$list_id],
]),
]);
}
);
$request->wait();
The variables $account_data and $api are defined higher up in my function and I’m able to access them when I created the initial promise using Guzzle (and it creates the user), but, when I try to use $api again inside of .then() it tells me that it is undefined.
How can I access $api (without global) / what am I missing here?
>Solution :
You cannot use variables defined outside of the anonymous function without either passing them as parameters, or by explicitly importing them with a use() statement. So your function would need to look something like:
$request->then(
function (ResponseInterface $res) use ($api, $data, $account_data, $list_id) {
$api->post('v1/subscribers/' . $data['email'] . '/segments', [
'auth' => [$account_data['api_key'], ''],
'headers' => [
'Content-Type' => 'application/json',
],
'body' => json_encode([
'segment_ids' => [$list_id],
]),
]);
}
);
See: Example #3 in the docs.