VOOZH about

URL: https://deepwiki.com/hypervel/api-client/7.4-creating-custom-middleware

⇱ Creating Custom Middleware | hypervel/api-client | DeepWiki


Loading...
Menu

Creating Custom Middleware

This document provides a comprehensive guide for implementing custom middleware classes in the hypervel/api-client library. It covers both request and response middleware, explaining the contracts, implementation patterns, and best practices for extending the middleware system.

For an overview of the middleware pipeline architecture and how middleware is applied, see Understanding Middleware. For detailed documentation of the base middleware classes, see Request Middleware and Response Middleware.

Purpose and Scope

Custom middleware allows you to inject cross-cutting concerns into the request/response pipeline. By extending the abstract RequestMiddleware or ResponseMiddleware classes, you can:

  • Modify outgoing API requests (headers, body, authentication)
  • Transform incoming API responses (parsing, validation, error handling)
  • Implement logging, rate limiting, caching, and other concerns
  • Standardize behavior across multiple API endpoints

This document focuses on the implementation details of creating custom middleware. Configuration and registration are covered in Configuration.


Middleware Contract Overview

The middleware system provides two abstract base classes that handle PSR-7 conversion and define the contract for custom implementations.

Class Structure


Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18

Invocation Flow

The __invoke magic method serves as the adapter between PSR-7 interfaces and the domain-specific ApiRequest/ApiResponse types:

Class__invoke ReceivesConverts Tohandle MethodConverts Back
RequestMiddlewareRequestInterfaceApiRequestProcesses requestRequestInterface
ResponseMiddlewareResponseInterfaceApiResponseProcesses responseResponseInterface

The conversion process is handled automatically:

  1. Request Flow: PSR-7 RequestInterfacenew ApiRequest($request) → your handle() method → toPsrRequest()
  2. Response Flow: PSR-7 ResponseInterfacenew ApiResponse($response) → your handle() method → toPsrResponse()

Sources: src/RequestMiddleware.php11-15 src/ResponseMiddleware.php11-15


Creating Request Middleware

Request middleware intercepts and modifies outgoing API requests before they are sent to the HTTP client.

Implementation Steps

Step 1: Extend the Base Class

Create a new class that extends Hypervel\ApiClient\RequestMiddleware:


Step 2: Implement the handle Method

The handle method receives an ApiRequest instance and must return an ApiRequest instance. You can:

  • Chain fluent methods to modify the request
  • Return the modified request
  • Use conditional logic to selectively apply modifications

Sources: src/RequestMiddleware.php17

Request Middleware Data Flow


Sources: src/RequestMiddleware.php11-15

Example: Authentication Middleware

This example adds a Bearer token to all outgoing requests:


The withToken method is provided by ApiRequest and automatically formats the Authorization header correctly.

Example: User Agent Middleware

This example sets a consistent User-Agent header:


Example: Content Type Enforcement

This example ensures all requests use JSON content type:


Sources: src/RequestMiddleware.php1-18


Creating Response Middleware

Response middleware intercepts and processes incoming API responses after they are received from the HTTP client.

Implementation Steps

Step 1: Extend the Base Class

Create a new class that extends Hypervel\ApiClient\ResponseMiddleware:


Step 2: Implement the handle Method

The handle method receives an ApiResponse instance and must return an ApiResponse instance. Unlike request middleware, response middleware typically:

  • Inspects response status and headers
  • Validates response structure
  • Throws exceptions for error conditions
  • Logs response data
  • Transforms response content

Sources: src/ResponseMiddleware.php17

Response Middleware Data Flow


Sources: src/ResponseMiddleware.php11-15

Example: Error Detection Middleware

This example throws exceptions for HTTP error status codes:


Example: Response Logging Middleware

This example logs response details for debugging:


Example: Response Validation Middleware

This example validates that responses contain expected structure:


Sources: src/ResponseMiddleware.php1-18


Middleware Method Reference

Available Methods on ApiRequest

The ApiRequest class provides methods for modifying outgoing requests:

MethodParametersDescription
withHeader()string $name, string $valueAdd/replace a single header
withHeaders()array $headersAdd/replace multiple headers
withToken()string $token, string $type = 'Bearer'Add authentication token
withBasicAuth()string $username, string $passwordAdd HTTP Basic authentication
withQueryParameters()array $parametersAdd query string parameters
withBody()string $bodySet request body
asJson()-Set Content-Type to application/json
asForm()-Set Content-Type to application/x-www-form-urlencoded
toPsrRequest()-Convert to PSR-7 RequestInterface

For complete documentation of these methods, see ApiRequest.

Available Methods on ApiResponse

The ApiResponse class provides methods for inspecting responses:

MethodParametersDescription
status()-Get HTTP status code
successful()-Check if status is 2xx
failed()-Check if status is 4xx/5xx
clientError()-Check if status is 4xx
serverError()-Check if status is 5xx
header()string $nameGet single header value
headers()-Get all headers
body()-Get raw response body
json()string $key = nullParse JSON response
toPsrResponse()-Convert to PSR-7 ResponseInterface

For complete documentation of these methods, see ApiResponse.

Sources: src/RequestMiddleware.php13 src/ResponseMiddleware.php13


Best Practices

Single Responsibility Principle

Each middleware class should handle one specific concern. Avoid creating middleware that performs multiple unrelated tasks:

Good:


Avoid:


Immutability

Always return modified copies rather than mutating the input. The fluent interface on ApiRequest and ApiResponse already follows this pattern:


Dependency Injection

Use constructor injection for dependencies rather than accessing global state:


Error Handling

Response middleware should handle errors gracefully. Consider whether to throw exceptions or return error responses:


Conditional Processing

Use guard clauses to skip unnecessary processing:


Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18


Complete Implementation Example

This example demonstrates a complete custom middleware implementation that combines request and response processing:

Request Correlation Middleware


Response Correlation Middleware


Registration Pattern


Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18


Middleware Execution Order

Understanding execution order is crucial when multiple middleware classes are configured:


Order Considerations

PhaseExecution OrderUse Case Example
RequestArray order (0 → n)Auth → Logging → Rate Limiting
ResponseArray order (0 → n)Error Detection → Validation → Logging

Example Configuration:


Sources: src/RequestMiddleware.php11-15 src/ResponseMiddleware.php11-15


Common Use Cases

Rate Limiting


Request/Response Caching


Retry Logic


Request Signing


Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18


Testing Custom Middleware

Unit Testing Pattern


Integration Testing Pattern


Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18


Summary

Custom middleware in hypervel/api-client follows a simple pattern:

  1. Extend either RequestMiddleware or ResponseMiddleware
  2. Implement the abstract handle() method
  3. Receive domain-specific types (ApiRequest or ApiResponse)
  4. Return modified instances using fluent methods
  5. Register in client configuration

The __invoke method handles all PSR-7 conversion automatically, allowing you to focus on business logic using the rich ApiRequest and ApiResponse interfaces.

For details on registering and configuring middleware, see Configuration. For information about the middleware pipeline execution, see Understanding Middleware.

Sources: src/RequestMiddleware.php1-18 src/ResponseMiddleware.php1-18

Refresh this wiki

On this page