|
| 1 | +Events |
| 2 | +====== |
| 3 | + |
| 4 | +[[\yii\httpclient\Request]] provides several events, which can be handled via event handler or behavior: |
| 5 | + |
| 6 | +- [[\yii\httpclient\Request::EVENT_BEFORE_SEND]] - raised before sending request. |
| 7 | +- [[\yii\httpclient\Request::EVENT_AFTER_SEND]] - raised after sending request. |
| 8 | + |
| 9 | +These events may be used to adjust request parameters or received response. |
| 10 | +For example: |
| 11 | + |
| 12 | +```php |
| 13 | +use yii\httpclient\Client; |
| 14 | +use yii\httpclient\Request; |
| 15 | +use yii\httpclient\RequestEvent; |
| 16 | + |
| 17 | +$client = new Client(); |
| 18 | + |
| 19 | +$request = $client->createRequest() |
| 20 | + ->setMethod('get') |
| 21 | + ->setUrl('http://api.domain.com') |
| 22 | + ->setData(['param' => 'value']); |
| 23 | + |
| 24 | +// Ensure signature generation based on final data set: |
| 25 | +$request->on(Request::EVENT_BEFORE_SEND, function (RequestEvent $event) { |
| 26 | + $data = $event->request->getData(); |
| 27 | + |
| 28 | + $signature = md5(http_build_query($data)); |
| 29 | + $data['signature'] = $signature; |
| 30 | + |
| 31 | + $event->request->setData($data); |
| 32 | +}); |
| 33 | + |
| 34 | +// Normalize response data: |
| 35 | +$request->on(Request::EVENT_AFTER_SEND, function (RequestEvent $event) { |
| 36 | + $data = $event->response->getData(); |
| 37 | + |
| 38 | + $data['content'] = base64_decode($data['encoded_content']); |
| 39 | + |
| 40 | + $event->response->setData($data); |
| 41 | +}); |
| 42 | + |
| 43 | +$response = $request->send(); |
| 44 | +``` |
| 45 | + |
| 46 | +Attaching event handlers to the [[\yii\httpclient\Request]] instance is not very practical. |
| 47 | +You may handle same use cases using events of [[\yii\httpclient\Client]] class: |
| 48 | + |
| 49 | +- [[\yii\httpclient\Client::EVENT_BEFORE_SEND]] - raised before sending request. |
| 50 | +- [[\yii\httpclient\Client::EVENT_AFTER_SEND]] - raised after sending request. |
| 51 | + |
| 52 | +These events are triggered for all requests created via client in the same way and with the same signature as |
| 53 | +the ones from [[\yii\httpclient\Request]]. |
| 54 | +For example: |
| 55 | + |
| 56 | +```php |
| 57 | +use yii\httpclient\Client; |
| 58 | +use yii\httpclient\RequestEvent; |
| 59 | + |
| 60 | +$client = new Client(); |
| 61 | + |
| 62 | +$client->on(Client::EVENT_BEFORE_SEND, function (RequestEvent $event) { |
| 63 | + // ... |
| 64 | +}); |
| 65 | +$client->on(Client::EVENT_AFTER_SEND, function (RequestEvent $event) { |
| 66 | + // ... |
| 67 | +}); |
| 68 | +``` |
| 69 | + |
| 70 | +> Note: [[\yii\httpclient\Client]] and [[\yii\httpclient\Request]] share the same names for `EVENT_BEFORE_SEND` and |
| 71 | + `EVENT_AFTER_SEND` events, so you can create behavior which can be applied for both of these classes. |
0 commit comments