Laravel HTTP Pool - Callback is a package that enhances the HTTP pool functionality in Laravel. It allows users to apply callbacks to the results of HTTP requests made using Laravel's HTTP pool. This makes it easier to process and manipulate the responses as needed.
You can install the package via Composer:
composer require cbaconnier/laravel-http-pool-callback
You must implement the HttpPoolAware
interface and use the HasHttpPool
trait in your repository classes.
This will allow you to register callbacks to be applied to the responses of the requests.
use GuzzleHttp\Promise\PromiseInterface;
use Cbaconnier\HttpPool\HttpPoolAware;
use Cbaconnier\HttpPool\HasHttpPool;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
class InvoiceRepository implements HttpPoolAware
{
use HasHttpPool;
public function findAsync(int $id): PromiseInterface
{
$promise = $this->http()->get("https://example.com/invoices/{$id}");
// Register the callback that will be executed on the response
$this->onPromiseResolved(function (Response $response) {
return new InvoiceDto($response->getBody()->getContents());
});
return $promise;
}
public function find(int $id): InvoiceDto
{
// You can still use the repository without async requests as well
$response = $this->http()->get("https://example.com/invoices/{$id}");
return new InvoiceDto($response->getBody()->getContents());
}
// Not necessary but here to demonstrate a common use case
// Then use $this->client()->get(...) instead of $this->http()->get(...)
public function client(): PendingRequest
{
return $this->http()
->withHeaders([
'Authorizations' => 'Bearer ...'
])
->withOptions([
// ..
]);
}
}
runAsync
will clone your repositories instances to no infer with other requests and delegate the requests to the native Http::pool()
method.
By doing so, you can still benefit from the Http
methods and testing helpers.
When you call getResponses
, it will returns the default Laravel Response
objects.
When you call getResolved
, it will apply the callbacks
to the responses and returns the results.
use Cbaconnier\HttpPool\Facades\HttpPool;
$pool = HttpPool::runAsync([
'invoice' => $invoiceRepository->async(fn (InvoiceRepository $repository) => $repository->findAsync(123)),
'client' => $clientRepository->async(fn (ClientRepository $repository) => $repository->findAsync(123)),
]);
$pool->getResponses(); // Returns ['invoice' => Response, 'client' => Response]
$pool->getResolved(); // Returns ['invoice' => InvoiceDto, 'client' => ClientDto]
// You can also use macro instead of facade
Http::runAsync([ ... ])->getResolved();
composer test
If you discover any security related issues, please email the author instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.