@@ -152,3 +152,66 @@ RandomClientPool
152
152
****************
153
153
154
154
``RandomClientPool `` randomly choose an available client, throw a ``NotFoundHttpClientException `` if none are available.
155
+
156
+
157
+ HTTP Client Router
158
+ ------------------
159
+
160
+ This client accepts pairs of clients (both sync and async) and request matchers.
161
+ Every request is "routed" through this single client, checked against the request matchers
162
+ and sent using the first matched client. If there is no matching client, an exception is thrown.
163
+
164
+ This allows a single client to be used for different requests.
165
+
166
+ In the following example we use the client router to access an API protected by basic auth
167
+ and also to download an image from a static host::
168
+
169
+ use Http\Client\Common\HttpClientRouter;
170
+ use Http\Client\Common\PluginClient;
171
+ use Http\Client\Common\Plugin\AuthenticationPlugin;
172
+ use Http\Discovery\HttpClientDiscovery;
173
+ use Http\Discovery\MessageFactoryDiscovery;
174
+ use Http\Message\Authentication\BasicAuth;
175
+ use Http\Message\RequestMatcher\RequestMatcher;
176
+
177
+ $client = new HttpClientRouter();
178
+
179
+ $requestMatcher = new RequestMatcher(null, 'api.example.com');
180
+ $pluginClient = new PluginClient(
181
+ HttpClientDiscovery::find(),
182
+ [new AuthenticationPlugin(new BasicAuth('user', 'password'))]
183
+ );
184
+
185
+ $client->addClient($pluginClient, $requestMatcher);
186
+
187
+
188
+ $requestMatcher = new RequestMatcher(null, 'images.example.com');
189
+
190
+ $client->addClient(HttpClientDiscovery::find(), $requestMatcher);
191
+
192
+
193
+ $messageFactory = MessageFactoryDiscovery::find();
194
+
195
+ // Get the user data
196
+ $request = $messageFactory->createRequest('GET', 'https://api.example.com/user/1');
197
+
198
+ $response = $client->send($request);
199
+ $imagePath = json_decode((string) $response->getBody(), true)['image_path'];
200
+
201
+ // Download the image
202
+ $request = $messageFactory->createRequest('GET', 'https://images.example.com/user/'.$imagePath);
203
+
204
+ $response = $client->send($request);
205
+
206
+ file_put_contents('path/to/images/'.$imagePath, (string) $response->getBody());
207
+
208
+ $request = $messageFactory->createRequest('GET', 'https://api2.example.com/user/1');
209
+
210
+ // Throws an Http\Client\Exception\RequestException
211
+ $client->send($request);
212
+
213
+
214
+ .. note ::
215
+
216
+ Simple routing can be achieved with the ``RequestConditionalPlugin `` and the ``PluginClient ``,
217
+ but in that case the routing logic is integrated into the linear request flow.
0 commit comments