Skip to content

Commit c4ff918

Browse files
committed
Merge branch '4.4'
* 4.4: [HttpClient] tell about ScopingHttpClient::forBaseUri()
2 parents b5e5d4d + 8056c09 commit c4ff918

File tree

1 file changed

+48
-31
lines changed

1 file changed

+48
-31
lines changed

components/http_client.rst

Lines changed: 48 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,8 @@ low-level HTTP client that makes requests, like the following ``GET`` request::
2626

2727
use Symfony\Component\HttpClient\HttpClient;
2828

29-
$httpClient = HttpClient::create();
30-
$response = $httpClient->request('GET', 'https://api.github.com/repos/symfony/symfony-docs');
29+
$client = HttpClient::create();
30+
$response = $client->request('GET', 'https://api.github.com/repos/symfony/symfony-docs');
3131

3232
$statusCode = $response->getStatusCode();
3333
// $statusCode = 200
@@ -63,10 +63,10 @@ the transport explicitly, use the following classes to create the client::
6363
use Symfony\Component\HttpClient\NativeHttpClient;
6464

6565
// uses native PHP streams
66-
$httpClient = new NativeHttpClient();
66+
$client = new NativeHttpClient();
6767

6868
// uses the cURL PHP extension
69-
$httpClient = new CurlHttpClient();
69+
$client = new CurlHttpClient();
7070

7171
When using this component in a full-stack Symfony application, this behavior is
7272
not configurable and cURL will be used automatically if the cURL PHP extension
@@ -79,7 +79,7 @@ When requesting an ``https`` URL, HTTP/2 is enabled by default if libcurl >= 7.3
7979
is used. To force HTTP/2 for ``http`` URLs, you need to enable it explicitly via
8080
the ``http_version`` option::
8181

82-
$httpClient = HttpClient::create(['http_version' => '2.0']);
82+
$client = HttpClient::create(['http_version' => '2.0']);
8383

8484
Support for HTTP/2 PUSH works out of the box when libcurl >= 7.61 is used with
8585
PHP >= 7.2.17 / 7.3.4: pushed responses are put into a temporary cache and are
@@ -91,16 +91,16 @@ Making Requests
9191
The client created with the ``HttpClient`` class provides a single ``request()``
9292
method to perform all kinds of HTTP requests::
9393

94-
$response = $httpClient->request('GET', 'https://...');
95-
$response = $httpClient->request('POST', 'https://...');
96-
$response = $httpClient->request('PUT', 'https://...');
94+
$response = $client->request('GET', 'https://...');
95+
$response = $client->request('POST', 'https://...');
96+
$response = $client->request('PUT', 'https://...');
9797
// ...
9898

9999
Responses are always asynchronous, so that the call to the method returns
100100
immediately instead of waiting to receive the response::
101101

102102
// code execution continues immediately; it doesn't wait to receive the response
103-
$response = $httpClient->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');
103+
$response = $client->request('GET', 'http://releases.ubuntu.com/18.04.2/ubuntu-18.04.2-desktop-amd64.iso');
104104

105105
// getting the response headers waits until they arrive
106106
$contentType = $response->getHeaders()['content-type'][0];
@@ -125,7 +125,7 @@ defined globally when creating the client (to apply it to all requests) and to
125125
each request (which overrides any global authentication)::
126126

127127
// Use the same authentication for all requests
128-
$httpClient = HttpClient::create([
128+
$client = HttpClient::create([
129129
// HTTP Basic authentication (there are multiple ways of configuring it)
130130
'auth_basic' => ['the-username'],
131131
'auth_basic' => ['the-username', 'the-password'],
@@ -140,7 +140,7 @@ each request (which overrides any global authentication)::
140140
'auth_ntlm' => 'the-username:the-password',
141141
]);
142142

143-
$response = $httpClient->request('GET', 'https://...', [
143+
$response = $client->request('GET', 'https://...', [
144144
// use a different HTTP Basic authentication only for this request
145145
'auth_basic' => ['the-username', 'the-password'],
146146

@@ -158,7 +158,7 @@ You can either append them manually to the requested URL, or define them as an
158158
associative array via the ``query`` option, that will be merged with the URL::
159159

160160
// it makes an HTTP GET request to https://httpbin.org/get?token=...&name=...
161-
$response = $httpClient->request('GET', 'https://httpbin.org/get', [
161+
$response = $client->request('GET', 'https://httpbin.org/get', [
162162
// these values are automatically encoded before including them in the URL
163163
'query' => [
164164
'token' => '...',
@@ -173,13 +173,13 @@ Use the ``headers`` option to define both the default headers added to all
173173
requests and the specific headers for each request::
174174

175175
// this header is added to all requests made by this client
176-
$httpClient = HttpClient::create(['headers' => [
176+
$client = HttpClient::create(['headers' => [
177177
'User-Agent' => 'My Fancy App',
178178
]]);
179179

180180
// this header is only included in this request and overrides the value
181181
// of the same header if defined globally by the HTTP client
182-
$response = $httpClient->request('POST', 'https://...', [
182+
$response = $client->request('POST', 'https://...', [
183183
'headers' => [
184184
'Content-Type' => 'text/plain',
185185
],
@@ -192,7 +192,7 @@ This component provides several methods for uploading data using the ``body``
192192
option. You can use regular strings, closures, iterables and resources and they'll be
193193
processed automatically when making the requests::
194194

195-
$response = $httpClient->request('POST', 'https://...', [
195+
$response = $client->request('POST', 'https://...', [
196196
// defining data using a regular string
197197
'body' => 'raw data',
198198

@@ -225,7 +225,7 @@ A generator or any ``Traversable`` can also be used instead of a closure.
225225
given content will be JSON-encoded automatically and the request will add the
226226
``Content-Type: application/json`` automatically too::
227227

228-
$response = $httpClient->request('POST', 'https://...', [
228+
$response = $client->request('POST', 'https://...', [
229229
'json' => ['param1' => 'value1', '...'],
230230
]);
231231

@@ -268,7 +268,7 @@ making a request. Use the ``max_redirects`` setting to configure this behavior
268268
(if the number of redirects is higher than the configured value, you'll get a
269269
:class:`Symfony\\Component\\HttpClient\\Exception\\RedirectionException`)::
270270

271-
$response = $httpClient->request('GET', 'https://...', [
271+
$response = $client->request('GET', 'https://...', [
272272
// 0 means to not follow any redirect
273273
'max_redirects' => 0,
274274
]);
@@ -297,7 +297,7 @@ uploads/downloads as they complete. This callback is guaranteed to be called on
297297
DNS resolution, on arrival of headers and on completion; additionally it is
298298
called when new data is uploaded or downloaded and at least once per second::
299299

300-
$response = $httpClient->request('GET', 'https://...', [
300+
$response = $client->request('GET', 'https://...', [
301301
'on_progress' => function (int $dlNow, int $dlSize, array $info): void {
302302
// $dlNow is the number of bytes downloaded so far
303303
// $dlSize is the total size to be downloaded or -1 if it is unknown
@@ -322,7 +322,7 @@ The response returned by all HTTP clients is an object of type
322322
:class:`Symfony\\Contracts\\HttpClient\\ResponseInterface` which provides the
323323
following methods::
324324

325-
$response = $httpClient->request('GET', 'https://...');
325+
$response = $client->request('GET', 'https://...');
326326

327327
// gets the HTTP status code of the response
328328
$statusCode = $response->getStatusCode();
@@ -361,7 +361,7 @@ Call the ``stream()`` method of the HTTP client to get *chunks* of the
361361
response sequentially instead of waiting for the entire response::
362362

363363
$url = 'https://releases.ubuntu.com/18.04.1/ubuntu-18.04.1-desktop-amd64.iso';
364-
$response = $httpClient->request('GET', $url, [
364+
$response = $client->request('GET', $url, [
365365
// optional: if you don't want to buffer the response in memory
366366
'buffer' => false,
367367
]);
@@ -374,7 +374,7 @@ response sequentially instead of waiting for the entire response::
374374
// get the response contents in chunk and save them in a file
375375
// response chunks implement Symfony\Contracts\HttpClient\ChunkInterface
376376
$fileHandler = fopen('/ubuntu.iso', 'w');
377-
foreach ($httpClient->stream($response) as $chunk) {
377+
foreach ($client->stream($response) as $chunk) {
378378
fwrite($fileHandler, $chunk->getContent());
379379
}
380380

@@ -408,7 +408,7 @@ When the HTTP status code of the response is in the 300-599 range (i.e. 3xx,
408408
``getHeaders()`` and ``getContent()`` methods throw an appropriate exception::
409409

410410
// the response of this request will be a 403 HTTP error
411-
$response = $httpClient->request('GET', 'https://httpbin.org/status/403');
411+
$response = $client->request('GET', 'https://httpbin.org/status/403');
412412

413413
// this code results in a Symfony\Component\HttpClient\Exception\ClientException
414414
// because it doesn't check the status code of the response
@@ -603,25 +603,42 @@ class to autoconfigure the HTTP client based on the requested URL::
603603
'Authorization' => 'token '.$githubToken,
604604
],
605605
],
606+
// ...
606607
]);
607608

609+
You can define several scopes, so that each set of options is added only if a
610+
requested URL matches one of the regular expressions provided as keys.
611+
608612
If the request URL is relative (because you use the ``base_uri`` option), the
609613
scoping HTTP client can't make a match. That's why you can define a third
610614
optional argument in its constructor which will be considered the default
611615
regular expression applied to relative URLs::
612616

613617
// ...
614618

615-
$httpClient = new ScopingHttpClient($client, [
616-
'https://api\.github\.com/' => [
617-
'base_uri' => 'https://api.github.com/',
618-
// ...
619+
$client = new ScopingHttpClient($client,
620+
[
621+
'https://api\.github\.com/' => [
622+
'base_uri' => 'https://api.github.com/',
623+
// ...
624+
],
619625
],
620-
],
621-
// this is the regexp applied to all relative URLs
626+
// this is the index in the previous array that defines
627+
// the base URI that shoud be used to resolve relative URLs
622628
'https://api\.github\.com/'
623629
);
624630

631+
The above example can be reduced to a simpler call::
632+
633+
// ...
634+
635+
$client = ScopingHttpClient::forBaseUri($client, 'https://api.github.com/', [
636+
// ...
637+
]);
638+
639+
This way, the provided options will be used only if the requested URL is relative
640+
or if it matches the ``https://api.github.com/`` base URI.
641+
625642
Interoperability
626643
----------------
627644

@@ -795,11 +812,11 @@ into any services by type-hinting a constructor argument with the
795812

796813
class SomeService
797814
{
798-
private $httpClient;
815+
private $client;
799816

800-
public function __construct(HttpClientInterface $httpClient)
817+
public function __construct(HttpClientInterface $client)
801818
{
802-
$this->httpClient = $httpClient;
819+
$this->client = $client;
803820
}
804821
}
805822

0 commit comments

Comments
 (0)