Basic Usage
Obtain Http Client
To obtain a Http Client instance, use the HttpClientsManager
. It can be obtained via HttpClientsManagerTrait
.
<?php
use Aedart\Http\Clients\Traits\HttpClientsManagerTrait;
class WeatherController
{
use HttpClientsManagerTrait;
public function index()
{
$client = $this->getHttpClientsManager()->profile();
// ...remaining not shown
}
}
Obtain Specific Client Profile
In order to obtain a Http Client profile, state the profile name as argument for the profile()
method.
$myClient = $this->getHttpClientsManager()->profile('my-client-profile');
Fresh Client instance
Available since v5.19.0
The profile()
method will return the same Client
instance, if it was previously requested (it caches the created instance for the profile name). If you need a fresh instance, without having it cached by the client manager, then use the fresh()
method.
$client = $this->getHttpClientsManager()->fresh('my-client-profile');
Perform Http Requests
Each method that performs a request will return a PSR-7 ResponseInterface
.
GET
Use get()
to make a Http GET request.
$response = $client->get('/users');
HEAD
Use head()
to make a Http HEAD request.
$response = $client->head('/users');
POST
Use post()
to make a Http POST request.
$response = $client->post('/users', [
'name' => 'John Doe',
'job' => 'developer'
]);
PUT
Use put()
to make a Http PUT request.
$response = $client->put('/users/421', [
'name' => 'Jim Orion',
'job' => 'architect'
]);
DELETE
Use delete()
to make a Http DELETE request.
$response = $client->delete('/users/7742');
OPTIONS
Use options()
to make a Http OPTIONS request.
$response = $client->options('/users');
PATCH
Use patch()
to make a Http PATCH request.
$response = $client->patch('/users/4487', [
'name' => 'Isabella Amelia Thomason',
'job' => 'lead designer'
]);
Generic Request
The request()
method allows you to perform a generic Http request. It accepts three arguments:
$method
:string
Http method name$uri
:string
orUriInterface
The Uri$options
:array
Driver specific request options (See Guzzle's documentation for additional information)
$response = $client->request('PATCH', '/users/1247', [
'json' => [
'name' => 'Emma Jackson',
'job' => 'junior developer'
]
]);