2016-04-07 17 views
3

私の目的は、Guzzle 6を使用して、jsonデータをPUTする非同期要求のプールを作成することです。次に、$ promiseの成功/失敗を監視します。私のPOOLのコード例と比較するために Guzzle 6を使用してAPIエンドポイントに送信する非同期json要求のプールを作成する正しい方法は何ですか?

は、$クライアント - >リクエスト()を次のように単一の要求は、エンコードされたJSONに3番目のパラメータを変換し、コンテンツタイプ追加されます。アプリケーション/ JSONを**

$client = new Client([ 
    'base_uri' => BASE_URL . 'test/async/', // Base URI is used with relative requests 
    'timeout' => 0, // 0 no timeout for operations and watching Promises 
]); 

$response = $client->request('PUT', 'cool', ['json' => ['foo' => 'bar']]); 
受信APIエンドポイント上

、私は、次の手順を実行して、上記の単一の要求からJSONを読むことができます:新しい要求を(使用してconcurrent requests example in the docs, for creating a Pool of asynchronous requestsを使用して

$json = file_get_contents('php://input'); 
$json = json_decode($json, true); 

)、私が望んで上記の単一の$ client-> request()の例のように、同じパラメータ(メソッド、URLエンドポイント、jsonフラグ)を使用できます。しかし、yield new Request()$client->request()のような3番目のjsonパラメータを処理しません。 jsonとcontent-typeを正しく設定するためにプールコードから呼び出す正しいGuzzle関数は何ですか?または、非同期要求の大きなプールを作成し、その結果を監視するより良い方法がありますか?

POOLコード例:

$this->asyncRequests = [ 
    [ 
     'endpoint' => 'cool' 
    ], 
    [ 
     'endpoint' => 'awesome' 
    ], 
    [ 
     'endpoint' => 'crazy' 
    ], 
    [ 
     'endpoint' => 'weird' 
    ] 
]; 

$client = new Client([ 
    'base_uri' => BASE_URL, // Base URI is used with relative requests 
    'timeout' => 0 // 0 no timeout for operations and watching Promises 
]); 

$requests = function ($asyncRequests) { 
    $uri = BASE_URL . 'test/async/'; 

    foreach ($asyncRequests as $key => $data) { 
     yield new Request('PUT', "{$uri}{$data['endpoint']}", ['json' => ['foo' => 'bar']]); 
    } 
}; 

$pool = new Pool($client, $requests($this->asyncRequests), [ 
    'concurrency' => 10, 
    'fulfilled' => function ($response, $index) { 
     $this->handleSuccessPromises($response, $index); 
    }, 
    'rejected' => function ($reason, $index) { 
     $this->handleFailurePromises($reason, $index); 
    }, 
]); 

$promise = $pool->promise(); // Initiate the transfers and create a promise 

$promise->wait(); // Force the pool of requests to complete. 

答えて

8

うまくいけば、他の誰かが中にジャンプし、私の目的を達成するために、より正確な方法があるなら、私に知らせますが、がつがつ食うIにボンネットの下を見た後になります新しいRequest()の3番目のパラメーターがヘッダー情報を探していて、4番目のパラメーターが本文を探していることを認識しました。だから、次のコードは、プールを使用して:

foreach ($syncRequests as $key => $headers) { 
    yield new Request('PUT', "{$uri}{$headers['endpoint']}", ['Content-type' => 'application/json'], json_encode(['json' => ['nonce' => $headers['json']]])); 
} 

Also in docs for Psr7\Request enter image description here

+1

聖なるくそ!これを明確に説明してくれてありがとう! –

0

をあなたが完全に制御したい場合は、あなたのプールに要求()オブジェクトを使用していない動作します。代わりに、リクエストを開始するコール可能な関数を生成するプールのジェネレータを持つことによって、リクエストを自分で開始します。これにより、すべてのオプションを完全に制御できます。ここでは、正しいコードの例である:それは身体とJSONは、4番目のパラメータでなければならないことを実現するためにかかった時間の時間

https://stackoverflow.com/a/40622269/5562035

関連する問題