【发布时间】:2017-03-12 03:24:15
【问题描述】:
我需要使用 Guzzle 从我的数据库中检查很多项目。例如,项目数量为 2000-5000。将它全部加载到一个数组中太多了,所以我想将它分成块:SELECT * FROM items LIMIT 100。当最后一个项目发送到 Guzzle 时,接下来会请求 100 个项目。在“已完成”处理程序中,我应该知道哪个项目得到了响应。我看到我们这里有 $index,它指向当前项目的数量。但我无权访问 $items 变量可见的范围。无论如何,如果我什至通过 use($items) 访问它,那么在循环的第二遍中我得到错误的索引,因为 $items 数组中的索引将从 0 开始,而 $index 将> 100。所以,这种方法是行不通的。
$client = new Client();
$iterator = function() {
while($items = getSomeItemsFromDb(100)) {
foreach($items as $item) {
echo "Start item #{$item['id']}";
yield new Request('GET', $item['url']);
}
}
};
$pool = new Pool($client, $iterator(), [
'concurrency' => 20,
'fulfilled' => function (ResponseInterface $response, $index) {
// how to get $item['id'] here?
},
'rejected' => function (RequestException $reason, $index) {
call_user_func($this->error_handler, $reason, $index);
}
]);
$promise = $pool->promise();
$promise->wait();
我想如果我可以做类似的事情
$request = new Request('GET', $item['url']);
$request->item = $item;
然后在 'fulfilled' 处理程序中只是为了从 $response 获取 $request - 这将是理想的。但正如我所看到的,没有办法做像 $response->getRequest() 这样的事情。 有关如何解决此问题的任何建议?
【问题讨论】:
-
你可以返回一个数组
yield [ 'request' => new Request('GET', $item['url']), 'id' => $item['id'] ]; -
你找到解决办法了吗?