Skip to content

Instantly share code, notes, and snippets.

@rela589n
Last active June 15, 2024 11:55
Show Gist options
  • Save rela589n/60ec71dac817c54784dc38578332a59b to your computer and use it in GitHub Desktop.
Save rela589n/60ec71dac817c54784dc38578332a59b to your computer and use it in GitHub Desktop.
Non-blocking http requests in PHP
<?php
final class PricesHttpClient implements PricesClient
{
public function __construct(
// AMPHP http client (https://github.com/amphp/http-client)
private HttpClient $httpClient,
) {
}
/**
* @param list<string> $productIds
*
* @return Price[]
*/
public function getPrices(array $productIds): array
{
$response = $this->httpClient->request('GET', '/api/prices', [
'query' => [
'productIds' => implode(',', $productIds),
],
]);
$pricesArray = $response->getJsonArray();
return array_map(static fn ($unit) => Price::fromUnit($unit), $pricesArray);
}
}
final class PricesConcurrentClient implements PricesClient
{
public function __construct(
#[AutowireDecorated]
private PricesClient $client,
) {
}
/**
* @param list<string> $productIds
*
* @return Price[]
*/
public function getPrices(array $productIds): array
{
$chunks = array_chunk($productIds, 100);
$promises = [];
foreach ($chunks as $chunk) {
$promises [] = async(fn () => $this->client->getPrices($chunk));
}
/** @var Price[][] $prices */
$prices = await($promises);
return array_merge(...$prices);
}
}
$pricesClient = new PricesConcurrentClient(new PricesHttpClient($amphpHttpClient));
// async/await logic is hidden inside
$prices = $pricesClient->getPrices($productIds);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment