PHP应用程序中的Guzzle池
我正在尝试在PHP中使用Guzzle池。但是我在处理异步请求时遇到了困难。下面是代码片段。PHP应用程序中的Guzzle池,php,promise,guzzle,reactphp,Php,Promise,Guzzle,Reactphp,我正在尝试在PHP中使用Guzzle池。但是我在处理异步请求时遇到了困难。下面是代码片段。 $client = new \GuzzleHttp\Client(); function test() { $client = new \GuzzleHttp\Client(); $request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true
$client = new \GuzzleHttp\Client();
function test()
{
$client = new \GuzzleHttp\Client();
$request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);
$client->send($request)->then(function ($response) {
//echo 'Got a response! ' . $response;
return "\n".$response->getBody();
});
}
$res = test();
var_dump($res); // echoes null - I know why it does so but how to resolve the issue.
有人知道如何让函数等待并得到正确的结果。如果可以返回它,那么它在代码风格上就不是异步的。归还承诺,并在外面打开它
function test()
{
$client = new \GuzzleHttp\Client();
$request = $client->createRequest('GET', 'http://l/?n=0', ['future' => true]);
// note the return
return $client->send($request)->then(function ($response) {
//echo 'Got a response! ' . $response;
return "\n".$response->getBody();
});
}
test()->then(function($body){
echo $body; // access body here inside `then`
});
另外一个我想用guzzle 6、postAsync和Pool分享的例子
function postInBulk($inputs)
{
$client = new Client([
'base_uri' => 'https://a.b.com'
]);
$headers = [
'Authorization' => 'Bearer token_from_directus_user'
];
$requests = function ($a) use ($client, $headers) {
for ($i = 0; $i < count($a); $i++) {
yield function() use ($client, $headers) {
return $client->postAsync('https://a.com/project/items/collection', [
'headers' => $headers,
'json' => [
"snippet" => "snippet",
"rank" => "1",
"status" => "published"
]
]);
};
}
};
$pool = new Pool($client, $requests($inputs),[
'concurrency' => 5,
'fulfilled' => function (Response $response, $index) {
// this is delivered each successful response
},
'rejected' => function (RequestException $reason, $index) {
// this is delivered each failed request
},
]);
$pool->promise()->wait();
}
函数postInBulk($inputs)
{
$client=新客户端([
'基本uri'=>'https://a.b.com'
]);
$headers=[
“授权”=>“来自\u directus\u用户的承载令牌”
];
$requests=函数($a)使用($client,$headers){
对于($i=0;$ipostAsync('https://a.com/project/items/collection', [
'headers'=>$headers,
“json”=>[
“代码段”=>“代码段”,
“排名”=>“1”,
“状态”=>“已发布”
]
]);
};
}
};
$pool=新池($client,$requests,$input)[
“并发”=>5,
“已完成”=>函数(响应$Response,$index){
//每一次成功的响应都会传递此信息
},
“已拒绝”=>函数(RequestException$reason$index){
//这将在每个失败的请求中传递
},
]);
$pool->promise()->wait();
}