如何在Guzzle中链接两个http请求

时间:2017-04-19 06:17:47

标签: php guzzle guzzle6 guzzlehttp

我有2个http请求

  1. 通过mailchimp api创建一个新列表(将创建一个列表ID)

  2. 将新成员添加到新创建的列表中。

  3. 我对将它们链接在一起的语法有点困惑。 完整代码如下。这是正确的方法吗?

    <?php
    
    // auto load
    require 'vendor/autoload.php';
    
    use GuzzleHttp\Psr7\Request;
    
    // opt
    $option = array(
      'base_uri' => "https://us12.api.mailchimp.com/3.0/",
      'auth' => ['apikey', '292bae37c631ac3ba03ed0640b44e6c3'],
    );
    
    // client
    $client = new \GuzzleHttp\Client($option);
    
    // data for a new list
    $data_list = array(
      "name" => "test_mailchimp",
      "contact" => array(
        "company" => "MailChimp",
        "address1" => "675 Ponce De Leon Ave NE",
        "address2" => "Suite 5000",
        "city" => "Atlanta",
        "state" => "GA",
        "zip" => "30308",
        "country" => "US",
        "phone" => "12345678",
      ),
      "permission_reminder" => "You're receiving this email because you signed up for updates.",
      "use_archive_bar" => true,
      "campaign_defaults" => array(
        "from_name" => "test",
        "from_email" => "test@test.com",
        "subject" => "test_subject",
        "language" => "en",
      ),
        "notify_on_subscribe" => "",
        "notify_on_unsubscribe" => "",
        "email_type_option" => true,
        "visibility" => "pub",
    );
    
    
    // member data
    $data_member = array(
      'email_address' => 'member@member.com',
      "status" => "subscribed"
    );
    
    
    
    // common
    $headers = array(
      'User-Agent' => 'testing/1.0',
      'Accept'     => 'application/json'
    );
    
    
    
    // ------------- create a list -------------------
    // $data should match up the field, no json =>
    $url_display_list = 'lists';
    $req_create_list = new Request('POST', $url_display_list, $headers, json_encode($data_list));
    
    // promise
    $promise_create_list = $client
      ->sendAsync($req_create_list)
      ->then(function ($res) use ($headers, $data_member, $client) {
        $obj = json_decode($res->getBody());
        $list_id = $obj->id;
    
        // --------- add a member to list ---------
        $url_create_member = 'lists/'. $list_id. '/members';
        $req_create_member = new Request('POST', $url_create_member, $headers, json_encode($data_member));
    
        $promise_create_member = $client
          ->sendAsync($req_create_member)
          ->then(function ($res) use ($list_id) {
            $obj = json_decode($res->getBody());
            $member_id = $obj->id;
    
            echo "\n--- list id ----\n";
            echo "\n". $list_id. "\n";
    
            echo "\n--- member id ----\n";
            echo "\n". $member_id. "\n";
    
            // ------------ update a member ---------
    
    
          });
    
      });
    
    
    $promise_create_list->wait();
    $promise_create_member->wait();
    

1 个答案:

答案 0 :(得分:2)

要创建一系列操作,您只需要从->then()回调中返回新的承诺。

$finalPromise = $client->sendAsync('POST', $url1)->then(function (Response $response1) use ($client) {
    // Do something with the first response and prepare the second query.

    $secondPromise = $client->sendAsync('POST', $url2)->then(function (Response $response2) {
        // Decode JSON and/or do other stuff with the final results.

        return json_decode($response2->getBody()->getContents(), true);
    });

    return $secondPromise;
});

// The decoded JSON from the second query here.
$response2 = $finalPromise->wait();

或者您可以使用协程样式(它不太为人所知,但我会说更具可读性):

// The decoded JSON from the second query here.
$response2 = coroutine(function () use ($client) {
    $response1 = (yield $client->sendAsync('POST', $url1));

    // Do something with the first response and prepare the second query.

    $response2 = (yield $client->sendAsync('POST', $url2));
    // Decode JSON and/or do other stuff with the final results.

    // The final return value of the coroutine.
    yield json_decode($response2->getBody()->getContents(), true);
});