Skip to content

Commit f701891

Browse files
committed
Add info about HTTP client events.
Refs cakephp/cakephp#17416
1 parent 46fcecb commit f701891

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

en/core-libraries/httpclient.rst

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,59 @@ instead. You can force select a transport adapter using a constructor option::
479479

480480
$client = new Client(['adapter' => Stream::class]);
481481

482+
Events
483+
======
484+
485+
The HTTP client triggers couple of events before and after sending a request
486+
which allows you to modify either the request or response or do other tasks like
487+
caching, logging etc.
488+
489+
HttpClient.beforeSend
490+
---------------------
491+
492+
// Somewhere before calling one of the HTTP client's methods which makes a request
493+
$http->getEventManager()->on(
494+
'HttpClient.beforeSend',
495+
function (
496+
\Cake\Http\Client\ClientEvent $event,
497+
\Cake\Http\Client\Request $request,
498+
array $adapterOptions,
499+
int $redirects
500+
) {
501+
// Modify the request
502+
$event->setRequest(....);
503+
// Modify the adapter options
504+
$event->setAdapterOptions(....);
505+
506+
// Skip making the actual request by returning a response.
507+
// You can use $event->setResult($response) to achieve the same.
508+
return new \Cake\Http\Client\Response(body: 'something');
509+
}
510+
);
511+
512+
HttpClient.afterSend
513+
---------------------
514+
515+
// Somewhere before calling one of the HTTP client's methods which makes a request
516+
$http->getEventManager()->on(
517+
'HttpClient.afterSend',
518+
function (
519+
\Cake\Http\Client\ClientEvent $event,
520+
\Cake\Http\Client\Request $request,
521+
array $adapterOptions,
522+
int $redirects,
523+
bool $requestSent // Indicates whether the request was actually sent
524+
// or response returned from ``beforeSend`` event
525+
) {
526+
// Get the response
527+
$response = $event->getResponse();
528+
529+
// Return a new/modified response.
530+
// You can use $event->setResult($response) to achieve the same.
531+
return new \Cake\Http\Client\Response(body: 'something');
532+
}
533+
);
534+
482535
.. _httpclient-testing:
483536

484537
Testing

0 commit comments

Comments
 (0)