Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions en/core-libraries/httpclient.rst
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,59 @@ instead. You can force select a transport adapter using a constructor option::

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

Events
======

The HTTP client triggers couple of events before and after sending a request
which allows you to modify either the request or response or do other tasks like
caching, logging etc.

HttpClient.beforeSend
---------------------

// Somewhere before calling one of the HTTP client's methods which makes a request
$http->getEventManager()->on(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$http->getEventManager()->on(
$client->getEventManager()->on(

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All code examples above use the var $http for the client instance, hence I used the same for consistency.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The example on 480 uses $client. I can take care of normalizing them all though.

'HttpClient.beforeSend',
function (
\Cake\Http\Client\ClientEvent $event,
\Cake\Http\Client\Request $request,
array $adapterOptions,
int $redirects
) {
// Modify the request
$event->setRequest(....);
// Modify the adapter options
$event->setAdapterOptions(....);

// Skip making the actual request by returning a response.
// You can use $event->setResult($response) to achieve the same.
return new \Cake\Http\Client\Response(body: 'something');
}
);

HttpClient.afterSend
---------------------

// Somewhere before calling one of the HTTP client's methods which makes a request
$http->getEventManager()->on(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
$http->getEventManager()->on(
$client->getEventManager()->on(

'HttpClient.afterSend',
function (
\Cake\Http\Client\ClientEvent $event,
\Cake\Http\Client\Request $request,
array $adapterOptions,
int $redirects,
bool $requestSent // Indicates whether the request was actually sent
// or response returned from ``beforeSend`` event
) {
// Get the response
$response = $event->getResponse();

// Return a new/modified response.
// You can use $event->setResult($response) to achieve the same.
return new \Cake\Http\Client\Response(body: 'something');
}
);

.. _httpclient-testing:

Testing
Expand Down