VOOZH about

URL: https://deepwiki.com/hypervel/api-client/8.2-fluent-interface-patterns

⇱ Fluent Interface Patterns | hypervel/api-client | DeepWiki


Loading...
Menu

Fluent Interface Patterns

Purpose and Scope

This document explains the fluent interface design pattern as implemented throughout the Hypervel API Client codebase. A fluent interface enables method chaining by returning the object instance from methods, allowing readable, chainable configuration calls.

The fluent interface pattern is implemented across all core components: PendingRequest, ApiRequest, and ApiResponse. For information about how these components fit into the overall request lifecycle, see Core Architecture. For details on specific request configuration methods, see Request Configuration.

What is a Fluent Interface

A fluent interface is an object-oriented API design pattern that uses method chaining to create more readable code. Each method returns an instance of the object (typically $this or static), allowing subsequent methods to be called on the returned value in a single expression.

Traditional approach:


Fluent interface approach:


Fluent Interface Flow


Sources: General pattern analysis from src/PendingRequest.php67-167 src/ApiRequest.php24-212 src/ApiResponse.php14-66

Return Type Strategies

The codebase uses the static return type for all fluent interface methods. This is a strategic choice that provides specific benefits over alternative return type declarations.

Return TypeDescriptionBenefitsDrawbacks
staticLate static bindingWorks correctly with inheritance; subclasses return their own typeSlightly less specific than self
selfReturns the class where method is definedMore explicitBreaks inheritance; returns parent type in subclasses
$thisReturns the exact instanceMost specific in PHPDocNot available as native return type in PHP

The API client consistently uses static as the return type, which ensures that when subclasses extend ApiRequest, ApiResponse, or PendingRequest, the fluent interface continues to work correctly.

Example from ApiRequest:


Sources: src/ApiRequest.php48-51 src/ApiResponse.php36-42 src/PendingRequest.php67-72

Implementation in PendingRequest

The PendingRequest class implements fluent interfaces for configuring request execution behavior, middleware settings, and Guzzle options.

PendingRequest Fluent Methods


Method Categories in PendingRequest

CategoryMethodsReturn TypePurpose
Middleware ToggleenableMiddleware(), disableMiddleware()staticEnable/disable middleware pipeline
Middleware ConfigwithRequestMiddleware(), withResponseMiddleware()staticSet middleware arrays
Middleware AdditionwithAddedRequestMiddleware(), withAddedResponseMiddleware()staticAppend to existing middleware
OptionswithMiddlewareOptions(), withGuzzleOptions()staticConfigure execution options
Resource TypewithResource()staticSet custom resource class
Delegation__call()staticProxy to underlying HTTP client

Configuration Chaining Example


Sources: src/PendingRequest.php67-167 src/PendingRequest.php257-263

Implementation in ApiRequest

The ApiRequest class provides the most extensive fluent interface in the codebase, with over 20 chainable methods for building HTTP requests.

ApiRequest Method Categories


Immutable PSR-7 Integration

ApiRequest wraps a PSR-7 RequestInterface, which is immutable. Each fluent method creates a new PSR-7 request instance internally while maintaining the mutable fluent wrapper:


This hybrid approach allows for fluent chaining while maintaining PSR-7 compliance at the transport layer.

Data Modification Pattern

ApiRequest tracks whether data has been modified to defer expensive operations:


The data is only serialized and applied to the request body when toPsrRequest() is called src/ApiRequest.php217-224 optimizing performance when multiple data modifications occur.

Sources: src/ApiRequest.php24-29 src/ApiRequest.php48-63 src/ApiRequest.php78-105 src/ApiRequest.php126-137 src/ApiRequest.php182-212 src/ApiRequest.php217-240

Implementation in ApiResponse

The ApiResponse class provides a smaller but consistent fluent interface for modifying HTTP responses, primarily used by response middleware.

ApiResponse Fluent Methods

















































MethodParametersPurposeReturn Type
withStatus()int $code, string $reasonPhraseModify response status codestatic
withProtocolVersion()string $versionSet HTTP protocol versionstatic
withHeader()string $name, mixed $valueSet response headerstatic
withAddedHeader()string $name, mixed $valueAppend to existing headerstatic
withoutHeader()string $nameRemove response headerstatic
withBody()StreamInterface $bodyReplace response bodystatic

PSR-7 Response Wrapping

Like ApiRequest, ApiResponse wraps an immutable PSR-7 ResponseInterface:


Sources: src/ApiResponse.php14-20 src/ApiResponse.php36-66

Method Naming Conventions

The codebase follows consistent naming patterns for fluent interface methods, making the API intuitive and predictable.

Naming Pattern Reference

PrefixMeaningExampleBehavior
with*Sets or replaces a valuewithHeader(), withMethod()Replaces existing value
withAdded*Appends to existing valuewithAddedHeader(), withAddedRequestMiddleware()Adds to existing values
without*Removes a valuewithoutHeader(), withoutData()Removes specified value
as*Transforms request formatasJson(), asForm()Sets content type and format
accept*Sets Accept headeracceptJson(), accept()Configures response expectations
enable* / disable*Toggles featureenableMiddleware(), disableMiddleware()Boolean feature toggle

Naming Convention Flow


Consistency Across Classes

The naming conventions are consistent across all three fluent classes:

  • Header Methods: All three classes provide withHeader(), withAddedHeader(), withoutHeader()
  • Data Methods: Follow with* / without* pattern
  • Configuration: Use descriptive with* prefix for options

Sources: src/ApiRequest.php24-212 src/ApiResponse.php14-66 src/PendingRequest.php67-167

Integration with Magic Methods

The fluent interface pattern integrates with PHP's magic method system to provide delegation and proxy functionality.

Magic Method Delegation in PendingRequest

PendingRequest uses __call() to delegate unknown methods to the underlying HTTP client while maintaining fluent chaining:


This allows PendingRequest to expose all methods from ClientPendingRequest (from the hypervel/http-client package) without explicitly defining them.

Delegation Pattern Flow


Method Resolution Order

When a method is called on PendingRequest:

  1. Check local methods - If defined in PendingRequest, execute directly
  2. Check trait methods - If defined in Conditionable trait, execute
  3. Invoke __call() - Delegate to underlying HTTP client
  4. Return static - Maintain fluent chain

This creates a seamless API where client-specific configuration methods blend with HTTP client methods.

Sources: src/PendingRequest.php257-263 src/PendingRequest.php328-341

Type Safety with Generics

The fluent interface pattern in this codebase maintains type safety through PHP's generic type annotations, even though generics are not enforced at runtime.

Generic Type Flow


Return Type Preservation

Each fluent method in PendingRequest returns static (not self), preserving the generic type parameter:


The static return type ensures that when subclasses are created or when type parameters flow through the system, static analysis tools like PHPStan can track the specific resource type being returned.

Type Safety Benefits

AspectBenefitExample
IDE AutocompleteKnows methods available after chaining$client->withResource(User::class)->get() returns User
Static AnalysisCatches type errors before runtimePHPStan validates resource class compatibility
Refactoring SafetyFind all usages of specific typesRenaming CustomResource finds all references
DocumentationSelf-documenting API contractsGeneric annotations clarify return types

Sources: src/PendingRequest.php18-29 src/PendingRequest.php150-167 src/PendingRequest.php175-233

Best Practices and Patterns

Consistent Return Types

All fluent methods in the codebase return static:


Method Delegation Pattern

When one fluent method calls another, it directly returns the result to maintain the chain:


Conditional Execution with Fluent Interface

The PendingRequest class uses the Conditionable trait, which adds fluent conditional methods:


This pattern allows conditional configuration without breaking the fluent chain.

Sources: src/PendingRequest.php24 src/ApiRequest.php48-51


Summary: The fluent interface pattern is consistently implemented across PendingRequest, ApiRequest, and ApiResponse classes using static return types, consistent naming conventions (with*, without*, as*), and integration with magic methods for delegation. This design enables readable, chainable API configuration while maintaining type safety through generic type parameters and PSR-7 compliance through immutable request/response wrapping.

Refresh this wiki

On this page