VOOZH about

URL: https://deepwiki.com/hypervel/http-client/7-event-system

⇱ Event System | hypervel/http-client | DeepWiki


Loading...
Menu

Event System

Purpose and Scope

The Event System provides lifecycle hooks into the HTTP request/response cycle through a PSR-14 compatible event dispatcher. This document covers the three event types available, how to configure event dispatching, and common use cases for observability and monitoring.

For information about request/response handling outside of events, see Making HTTP Requests and Response Processing. For testing-related events, see Testing and Mocking.


Overview

The HTTP client dispatches three event types at critical points in the request lifecycle:

Event ClassTrigger PointContains
RequestSendingImmediately before request is sent to the networkRequest object
ResponseReceivedAfter successful response is receivedRequest and Response objects
ConnectionFailedWhen a connection error occursRequest and ConnectionException objects

The event system is optional. If no EventDispatcherInterface is provided to the Factory, event dispatch calls are silently skipped and have no performance impact.

Sources: src/Events/RequestSending.php1-18 src/Events/ResponseReceived.php1-21 src/Events/ConnectionFailed.php1-20


Event Lifecycle in Request Flow

The following diagram shows when each event is dispatched during a typical HTTP request:


Sources: src/PendingRequest.php202-209 src/PendingRequest.php731-794


Setting Up Event Dispatching

Event dispatching is configured by passing an EventDispatcherInterface implementation to the Factory constructor:


The Factory stores the dispatcher and makes it available to all PendingRequest instances it creates. Each PendingRequest retrieves the dispatcher from its factory when dispatching events.

Sources: src/Factory.php93-96 src/Factory.php420-425


Event Classes

RequestSending Event

The RequestSending event is dispatched immediately before the HTTP request is sent to the network layer. This occurs within the "before sending" handler in the middleware stack.

Event Structure:


Properties:

  • $request - The Request object containing the complete request details (URL, method, headers, body data)

Typical Use Cases:

  • Logging outgoing requests
  • Adding audit trails
  • Request metrics collection
  • Last-minute request validation

Dispatch Location: src/PendingRequest.php207

Sources: src/Events/RequestSending.php1-18 src/PendingRequest.php1254-1259


ResponseReceived Event

The ResponseReceived event is dispatched after a successful HTTP response is received and the Response object has been populated with cookies and transfer statistics.

Event Structure:


Properties:

  • $request - The Request object that was sent
  • $response - The Response object containing status code, headers, body, and metadata

Typical Use Cases:

  • Logging response status codes
  • Recording response times via transfer statistics
  • Collecting API usage metrics
  • Caching responses
  • Response validation

Dispatch Locations: src/PendingRequest.php738 (synchronous), src/PendingRequest.php859 (asynchronous)

Sources: src/Events/ResponseReceived.php1-21 src/PendingRequest.php1261-1266


ConnectionFailed Event

The ConnectionFailed event is dispatched when a network connection error occurs, such as DNS resolution failures, connection timeouts, or unreachable hosts.

Event Structure:


Properties:

  • $request - The Request object that failed
  • $exception - The ConnectionException containing error details and the underlying Guzzle ConnectException

Typical Use Cases:

  • Alerting on service unavailability
  • Connection failure logging
  • Circuit breaker pattern implementation
  • Network error metrics

Dispatch Locations: src/PendingRequest.php779 (synchronous), src/PendingRequest.php866 (asynchronous)

Sources: src/Events/ConnectionFailed.php1-20 src/PendingRequest.php1268-1273


Event Dispatching Implementation

The following diagram maps the event dispatch methods to their locations in the code:


Sources: src/PendingRequest.php1254-1273 src/Factory.php93


Event Dispatch Logic

Each dispatch method follows the same pattern to ensure event dispatching is optional:


The null-safe operator (?->) and conditional check ensure that:

  1. If no factory is present, no event is dispatched
  2. If the factory has no dispatcher, no event is dispatched
  3. Events are only dispatched when an EventDispatcherInterface is explicitly configured

Sources: src/PendingRequest.php1254-1259


Integration Points

The following table shows where events are dispatched in different request execution paths:

Execution PathRequestSendingResponseReceivedConnectionFailed
Synchronous Success✓ (line 207)✓ (line 738)-
Synchronous Connection Error✓ (line 207)-✓ (line 779)
Asynchronous Success✓ (line 207)✓ (line 859)-
Asynchronous Connection Error✓ (line 207)-✓ (line 866)
Stubbed/Faked Requests✓ (line 207)✓ (line 738/859)-

Note that stubbed requests (during testing) still dispatch events, allowing you to verify event handling in tests.

Sources: src/PendingRequest.php202-209 src/PendingRequest.php731-794 src/PendingRequest.php853-885


Common Use Cases

Request/Response Logging

Events provide complete request and response data for logging:


Metrics Collection

Track API usage patterns and performance:


Circuit Breaker Pattern

Implement failure detection for resilience:


Debug Tracing

Add distributed tracing identifiers:


Sources: src/Events/RequestSending.php1-18 src/Events/ResponseReceived.php1-21 src/Events/ConnectionFailed.php1-20


Events vs. Before Sending Callbacks

The event system differs from beforeSending() callbacks in several important ways:

FeatureEventsbeforeSending() Callbacks
PurposeObservability and monitoringRequest modification
TimingAfter request is finalizedBefore request is finalized
Can modify requestNoYes
Access to responseYes (for ResponseReceived)No
Global configurationVia Factory dispatcherVia Factory globalMiddleware
ScopeCross-cutting concernsRequest-specific logic

For request modification, use beforeSending() callbacks (see Middleware and Request Modification). For observability without modification, use events.

Sources: src/PendingRequest.php202-209 src/PendingRequest.php556-561


Event System Architecture


Sources: src/Factory.php93 src/PendingRequest.php1254-1273 src/Events/RequestSending.php1-18 src/Events/ResponseReceived.php1-21 src/Events/ConnectionFailed.php1-20


Performance Considerations

The event system is designed for minimal overhead:

  1. Lazy Check: Event dispatch methods check for dispatcher presence before creating event objects
  2. No Overhead When Disabled: If no dispatcher is configured, event dispatch is a null-safe property access with no object instantiation
  3. No Blocking: Event dispatch is synchronous but listeners should be non-blocking for optimal performance
  4. Testing Mode: Events are dispatched even when using fakes/stubs, with negligible overhead since no network calls occur

Sources: src/PendingRequest.php1254-1273