Skip to content

Commit fff1aa5

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

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

en/core-libraries/httpclient.rst

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -479,6 +479,60 @@ 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. You can use the global event manager to setup listeners
488+
for these events.
489+
490+
HttpClient.beforeSend
491+
---------------------
492+
493+
// Somewhere before calling one of the HTTP client's send methods.
494+
\Cake\Event\EventManager::instance()->on(
495+
'HttpClient.beforeSend',
496+
function (
497+
\Cake\Http\Client\ClientEvent $event,
498+
\Cake\Http\Client\Request $request,
499+
array $adapterOptions,
500+
int $redirects
501+
) {
502+
// Modify the request
503+
$event->setRequest(....);
504+
// Modify the adapter options
505+
$event->setAdapterOptions(....);
506+
507+
// Skip making the actual request by returning a response.
508+
// You can use $event->setResult($response) to achieve the same.
509+
return new \Cake\Http\Client\Response(body: 'something');
510+
}
511+
);
512+
513+
HttpClient.afterSend
514+
---------------------
515+
516+
// Somewhere before calling one of the HTTP client's send methods.
517+
\Cake\Event\EventManager::instance()->on(
518+
'HttpClient.afterSend',
519+
function (
520+
\Cake\Http\Client\ClientEvent $event,
521+
\Cake\Http\Client\Request $request,
522+
array $adapterOptions,
523+
int $redirects,
524+
bool $requestSent // Indicates whether the request was actually sent
525+
// or response returned from ``beforeSend`` event
526+
) {
527+
// Get the response
528+
$response = $event->getResponse();
529+
530+
// Return a new/modified response.
531+
// You can use $event->setResult($response) to achieve the same.
532+
return new \Cake\Http\Client\Response(body: 'something');
533+
}
534+
);
535+
482536
.. _httpclient-testing:
483537

484538
Testing

0 commit comments

Comments
 (0)