VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/4-http-client-component

⇱ HTTP Client Component | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

HTTP Client Component

The HTTP Client component provides a Laravel-style fluent API for making HTTP requests in Hyperf applications. Built on top of Guzzle with Swoole coroutine support, it offers a convenient interface for constructing requests, handling responses, and testing HTTP interactions. The component automatically detects coroutine contexts and uses the appropriate handler (CoroutineHandler when inside Swoole coroutines, standard handler otherwise).

For mail sending functionality, see Mail Component. For general helper functions including HTTP utilities, see Global Helper Functions.

Architecture Overview

The component is structured around three primary classes: Factory for creating request instances and managing test fakes, PendingRequest for building and executing requests, and Response for handling returned data. A static Http facade provides convenient access to the factory methods.

Architecture Diagram


Sources: src/http-client/src/Http.php106-217 src/http-client/src/Factory.php74-488 src/http-client/src/PendingRequest.php48-264

Request Building and Execution

PendingRequest Fluent API

The PendingRequest class provides a fluent interface for configuring HTTP requests. Each configuration method returns $this to enable method chaining. The class uses the Macroable and Conditionable traits for extensibility and conditional logic.

Configuration Methods

MethodPurposeExample Options
baseUrl(string)Set base URL for relative paths-
withHeaders(array)Add request headers['X-Custom' => 'value']
withToken(string, string)Add authorization tokenDefault type: 'Bearer'
withBasicAuth(string, string)HTTP basic authenticationusername, password
withDigestAuth(string, string)HTTP digest authenticationusername, password
withUserAgent(string)Set User-Agent header-
withCookies(array, string)Attach cookies for domain-
withQueryParameters(array)Add query string parametersMerged recursively
withUrlParameters(array)URL template substitutionUses UriTemplate::expand
timeout(int)Set timeout in secondsDefault: 30
connectTimeout(int)Set connection timeoutDefault: 10
withoutVerifying()Disable SSL verificationSets verify => false
withoutRedirecting()Disable redirectsSets allow_redirects => false
maxRedirects(int)Limit redirect count-

Body Format Methods


Sources: src/http-client/src/PendingRequest.php270-392 src/http-client/src/PendingRequest.php300-365

Handler Stack and Middleware System

The component constructs a Guzzle HandlerStack with multiple layers of middleware. The stack is built in buildHandlerStack() and populated by pushHandlers(). Middleware executes in reverse order of registration (last added, first executed).

Handler Stack Construction Process


Middleware Registration Methods

The component provides three methods for adding middleware:

  • withMiddleware(callable) - Adds raw middleware to the stack
  • withRequestMiddleware(callable) - Wraps with Middleware::mapRequest()
  • withResponseMiddleware(callable) - Wraps with Middleware::mapResponse()

Factory-level global middleware can be added via globalMiddleware(), globalRequestMiddleware(), and globalResponseMiddleware(), which are automatically passed to all PendingRequest instances.

Sources: src/http-client/src/PendingRequest.php956-991 src/http-client/src/PendingRequest.php643-671 src/http-client/src/Factory.php158-197

Request Execution Flow

The send() method orchestrates request execution with retry logic, error handling, and event dispatching. It normalizes URLs, parses options, and handles both synchronous and asynchronous requests.

Execution Pipeline


Sources: src/http-client/src/PendingRequest.php860-925 src/http-client/src/PendingRequest.php1342-1392

Before-Sending Callbacks

The beforeSending() method registers callbacks that execute immediately before request transmission. These callbacks receive the Request, options array, and PendingRequest instance. They can return a modified Request or RequestInterface to transform the request.

A default callback is registered in the constructor to capture the request object and cookies for later access, and to dispatch the RequestSending event.

Sources: src/http-client/src/PendingRequest.php679-684 src/http-client/src/PendingRequest.php1072-1090 src/http-client/src/PendingRequest.php257-262

Testing with Fakes and Assertions

Fake Registration and Stubbing

The Factory::fake() method enables request stubbing for testing. It accepts a callback or array mapping URL patterns to responses. When faked, requests are intercepted by the stub handler and never reach the network.

Fake Registration Patterns


Stubbing Methods

MethodSignaturePurpose
fake(?callable|array)Factory::fake($callback)Enable faking with callback or URL map
fakeSequence(string)Factory::fakeSequence($urlPattern)Create ResponseSequence for pattern
stubUrl(string, mixed)Factory::stubUrl($url, $callback)Stub specific URL pattern
preventStrayRequests(bool)Factory::preventStrayRequests()Throw if any request isn't faked
allowStrayRequests()Factory::allowStrayRequests()Allow unfaked requests

Sources: src/http-client/src/Factory.php236-274 src/http-client/src/Factory.php282-307 src/http-client/src/Http.php136-181

ResponseSequence

The ResponseSequence class provides sequential response faking. Each invocation shifts the next response from the queue. When empty, it throws OutOfBoundsException unless dontFailWhenEmpty() is called.

Response Sequence Methods


Example Usage Pattern (from tests):


Sources: src/http-client/src/ResponseSequence.php20-157 tests/HttpClient/HttpClientTest.php739-770

Assertion Methods

The Factory class records all request/response pairs when faking is enabled. It provides PHPUnit-compatible assertion methods for verifying HTTP interactions.

Assertion API

MethodParametersAssertion
assertSent(callable)callable(Request, Response)At least one request matches callback
assertNotSent(callable)callable(Request, Response)No requests match callback
assertSentInOrder(array)array<callable|string>Requests sent in specified order
assertNothingSent()-No requests recorded
assertSentCount(int)CountExact number of requests sent
assertSequencesAreEmpty()-All response sequences depleted
recorded(?callable)?callable(Request, Response)Get filtered collection of pairs

Request Assertion Helpers

The Request class provides methods for assertions within callbacks:

  • url() - Get full URL as string
  • method() - Get HTTP method
  • hasHeader(string, ?mixed) - Check header existence/value
  • hasHeaders(array|string) - Check multiple headers
  • header(string) - Get header values array
  • data() - Get decoded request body (form/JSON)
  • hasFile(string, ?string, ?string) - Check multipart file
  • isJson(), isForm(), isMultipart() - Content type checks

Sources: src/http-client/src/Factory.php360-455 src/http-client/src/Request.php21-311

Retry Logic and Error Handling

Retry Configuration

The retry() method configures automatic retry behavior for failed requests. It supports constant delays, exponential backoff via arrays, and conditional retry logic.

Retry Parameters


Backoff Array Behavior: When times is an array like [100, 200, 500], the component uses those values as millisecond delays between retries. The total tries becomes count($array) + 1 (one initial attempt plus retries).

Sources: src/http-client/src/PendingRequest.php610-622 src/http-client/src/PendingRequest.php878-924

Exception Handling

The component provides multiple methods for controlling error behavior. By default, failed requests (4xx/5xx) do not throw exceptions unless explicitly configured.

Error Handling Methods

MethodBehavior
throw(?callable)Throw RequestException on 4xx/5xx, optional callback
throwIf(bool|callable, ?callable)Conditional throwing
throwUnless(bool)Throw unless condition is true

Response Exception Methods

The Response class provides fine-grained exception control:

  • throw(?callable) - Throw if failed (4xx/5xx)
  • throwIf(bool|Closure) - Conditional throw
  • throwIfStatus(int|callable) - Throw if status matches
  • throwUnlessStatus(int|callable) - Throw unless status matches
  • throwIfClientError() - Throw on 4xx
  • throwIfServerError() - Throw on 5xx
  • toException() - Create exception without throwing

All throw methods accept an optional callback that receives (Response, RequestException) for custom error handling.

Connection Failures

When Guzzle throws a ConnectException, the component catches it, dispatches a ConnectionFailed event, and re-throws it wrapped as ConnectionException for consistent exception handling.

Sources: src/http-client/src/PendingRequest.php691-722 src/http-client/src/Response.php327-412 src/http-client/src/RequestException.php16-47

Concurrent Requests and Response Handling

Pool for Concurrent Requests

The Pool class enables sending multiple requests concurrently using Guzzle promises. Each request is automatically set to async mode and shares a common handler for efficient connection pooling.

Pool API Structure


Usage Pattern (from tests):


The pool() method on PendingRequest executes the callback with a Pool instance, then waits for all promises and returns an array of Response objects.

Sources: src/http-client/src/Pool.php19-90 src/http-client/src/PendingRequest.php841-852

Response Wrapper

The Response class wraps PSR-7 responses with convenience methods for accessing data and checking status. It implements ArrayAccess for direct JSON access and Stringable for body casting.

Response Data Accessors


Status Checking Methods

The DeterminesStatusCode trait provides boolean methods for HTTP status ranges:

MethodStatus RangeCommon Codes
successful()200-299200 OK, 201 Created, 204 No Content
ok()200OK
created()201Created
accepted()202Accepted
noContent()204No Content
redirect()300-399301, 302, 304
movedPermanently()301Moved Permanently
found()302Found
notModified()304Not Modified
clientError()400-499400, 401, 403, 404, 422
badRequest()400Bad Request
unauthorized()401Unauthorized
paymentRequired()402Payment Required
forbidden()403Forbidden
notFound()404Not Found
requestTimeout()408Request Timeout
conflict()409Conflict
unprocessableEntity()422Unprocessable Entity
tooManyRequests()429Too Many Requests
serverError()500+500, 502, 503
failed()clientError() || serverError()Any error

Additional methods: status(), reason(), headers(), header(string), cookies(), handlerStats(), effectiveUri(), close(), toPsrResponse().

Sources: src/http-client/src/Response.php26-458 src/http-client/src/Concerns/DeterminesStatusCode.php

Transfer Statistics

The PendingRequest populates transferStats on the response via Guzzle's on_stats callback. This provides timing information, effective URI after redirects, and handler-specific stats.

The populateResponse() method copies cookies and transferStats from the pending request to the response object after request completion.

Sources: src/http-client/src/PendingRequest.php1348-1356 src/http-client/src/PendingRequest.php1440-1450

HTTP Facade

The Http class provides static access to the Factory singleton. It resolves the factory from the container on first access and caches it. Special methods like fake(), fakeSequence(), and stubUrl() swap the resolved instance to ensure test isolation.

Facade Method Forwarding

All PendingRequest and Factory methods are available statically via @method annotations. The __callStatic() magic method forwards calls to the resolved factory instance.


Sources: src/http-client/src/Http.php106-217