SEO Metadata
SEO Title Options
- Building a PHP SDK: HTTP Client Abstraction, Retries
- Building a PHP SDK: HTTP Client Abstractio: Practical 2026
- APIs Playbook: Building a PHP SDK: HTTP Client Abstractio
Meta Description Options
- Learn Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes with a practical APIs framework, expert mistakes, implementation steps, examples, FAQ.
- Full tutorial for designing a third-party PHP SDK - fluent interface, PSR-18 HTTP client, retry middleware, and testable fakes.
URL Slug
building-php-sdk-http-client-abstraction-retries-test-fakes
Focus Keyword
Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes
Additional LSI Keywords
- APIs
- PHP
- SDK
- PSR-18
- Testing
- Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes
- production checklist
- implementation guide
- best practices
- architecture decisions
- testing strategy
- performance impact
Table of Contents
- Article overview
- What Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes means
- Why it matters now
- Implementation framework
- Practical comparison
- Expert workflow
- Common mistakes
- Media and link plan
- Original technical deep dive
- FAQ
- Structured data
- Conclusion
Article overview
Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes is the kind of topic that looks simple until it reaches production. Teams usually discover the real cost late: unclear boundaries, weak defaults, hidden maintenance work, and decisions that seemed harmless when the codebase was small.
The problem gets worse when the article, tutorial, or implementation guide only explains the happy path. This guide closes that gap with a practical framework, a comparison table, common mistakes, and a deep technical section you can use while planning real work.
Keep reading for the non-obvious part: the safest implementation is rarely the most impressive-looking one. It is the one your team can debug, test, document, and evolve without turning every future change into archaeology.
Key Takeaways
- Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes should be evaluated as a production decision, not only as a syntax or tooling choice.
- The best implementation keeps responsibilities visible, with clear ownership, tests, documentation, and rollback paths.
- Search visibility improves when practical depth, structured answers, and expert examples live on the same page.
[IMAGE: A mobile-first technical article layout showing the main concept, decision table, implementation checklist, and FAQ blocks. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes expert guide for APIs]
What Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes means
Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes means applying apis knowledge to a concrete engineering decision, then turning that decision into reliable code, documentation, and operational behavior. In practice, it combines the topic's core concepts with trade-off analysis, implementation boundaries, testing strategy, and maintenance discipline.
This is the definition worth optimizing for featured snippets because it avoids hype. It tells the reader what the topic does and what a professional implementation must include.
Why it matters now
The technical web is more crowded than it was a few years ago. Thin tutorials can still get indexed, but they rarely earn trust from senior developers, buyers, AI answer systems, or teams that need production guidance.
For apis topics, the strongest content now has three layers:
- a clear answer for fast scanning
- a practical framework for implementation
- expert context that explains what breaks later
That same structure helps search engines understand the page. It also helps readers decide whether the advice fits their project.
Implementation framework
Use this framework before adopting the approach described in this article.
- Define the user problem and the production risk.
- Identify the smallest reliable implementation boundary.
- Keep configuration, secrets, and environment-specific behavior outside the article's core logic.
- Add tests for the behavior that would hurt if it regressed.
- Document the trade-off, not only the final code.
- Measure the result with logs, metrics, or user-facing outcomes.
- Revisit the decision after real usage exposes edge cases.
The sequence is deliberately conservative. It keeps the work grounded in outcomes instead of novelty.
[IMAGE: A seven-step implementation framework with discovery, boundary design, configuration, tests, documentation, measurement, and iteration. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes implementation framework]
Practical comparison
| Decision area | Strong approach | Weak approach | Why it matters |
|---|---|---|---|
| Scope | Solve one clear problem | Mix unrelated concerns | Focus improves testing and search intent |
| Architecture | Put logic in explicit classes or documented boundaries | Hide behavior in templates or incidental callbacks | Future changes stay easier to review |
| Data flow | Pass prepared data into the view or endpoint | Query or compute in presentation code | Reduces regressions and performance surprises |
| Testing | Cover the risky behavior directly | Test only the happy path | Catches production failures earlier |
| Documentation | Explain trade-offs and limits | Repeat generic definitions | Builds E-E-A-T and reader trust |
| Operations | Track logs, metrics, and rollback steps | Ship without measurement | Makes the decision reversible |
This table is intentionally practical. It gives a reviewer something to check before the implementation becomes expensive to change.
Expert workflow
Expert tip: "Treat Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes as a system boundary. If the next developer cannot find where the decision lives, how it is tested, and when it should be avoided, the implementation is not finished."
A useful workflow is simple:
- Start with the smallest working example.
- Add the constraints that exist in your real project.
- Remove anything that only demonstrates cleverness.
- Write down the failure modes.
- Add links to related decisions so future readers can navigate the topic cluster.
That last point matters for both humans and search systems. A single article can answer a question; a cluster proves authority.
Common mistakes
Mistake 1: Copying a pattern without its context
A pattern that works in a small demo can fail in a real application. The missing context is usually data volume, team experience, deployment process, security requirements, or observability.
Before copying the pattern, ask what assumption made it safe in the original example.
Mistake 2: Putting business logic in the wrong layer
This is the fastest way to make future debugging expensive. In Laravel, PHP, and server-rendered websites, presentation should receive prepared data, not discover rules on its own.
Keep decision logic in models, actions, services, policies, requests, jobs, or documented helpers where it can be tested directly.
Mistake 3: Optimizing for novelty instead of maintainability
Newer tools and language features can be valuable. They can also hide simple behavior behind unfamiliar syntax.
Use the option that makes the next production incident easier to understand.
Mistake 4: Publishing without a measurement plan
If the article describes a performance, SEO, security, or architecture improvement, define how success will be checked. Logs, tests, crawl diagnostics, analytics, and user behavior are all stronger than assumptions.
[IMAGE: A common-mistakes board with context loss, wrong layer, novelty bias, and missing measurement highlighted. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes common mistakes]
Media and link plan
Image placeholders
- [IMAGE: A concept diagram for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes with input, decision boundary, implementation, tests, and production feedback. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes concept diagram]
- [IMAGE: A mobile screenshot-style checklist for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes mobile checklist]
- [IMAGE: A comparison table visualization for strong versus weak implementation choices. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes comparison table]
Video placeholder
[VIDEO: Insert a 5-8 minute YouTube walkthrough that demonstrates the main decision, the implementation boundary, the test strategy, and the production caveats for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes.]
Trustworthy outbound links
- PHP manual - use this as the trust reference for language-level reference.
- Google Search quality guidance - use this as the trust reference for people-first content and E-E-A-T alignment.
Internal linking opportunities
- Internal guide: PHP and AI: Integrating ChatGPT & Claude APIs - use this when readers need a related APIs follow-up.
- Internal guide: Building Webhooks in PHP: Payload Validation - use this when readers need a related APIs follow-up.
Original Technical Deep Dive
A PHP SDK should make the remote API feel boring.
The user should not think about URL assembly, authentication headers, JSON decoding, pagination, rate-limit responses, retry rules, or which HTTP client happens to be installed in their application.
The mistake is making the SDK a thin wrapper around Guzzle calls. That couples your package to one transport, makes tests noisy, and leaks low-level HTTP details into every resource method.
This guide was reviewed on May 7, 2026 against PHP-FIG PSR-7, PSR-17, PSR-18, PSR-3, RFC 9110, and Guzzle 7 documentation.
The short version
Build the SDK in layers:
| Layer | Owns | Should not own |
|---|---|---|
| Public client | Fluent entry point, resource accessors, configuration | Raw request execution |
| Resource classes | API paths, request DTOs, response mapping | Retry loops, sleeps, logging plumbing |
| Transport interface | SDK-level request/response contract | Vendor-specific HTTP client types |
| PSR-18 adapter | Converts SDK requests to PSR-7 and sends them | Business response mapping |
| Retry decorator | Retry policy, Retry-After, backoff, jitter | Deciding whether a domain operation is valid |
| Exceptions | Stable SDK errors | Exposing raw provider internals everywhere |
| Test fake | Queued responses and recorded requests | Real network calls |
Use PSR-18 for the HTTP client dependency, PSR-17 for request and stream factories, and PSR-7 for messages. Keep Guzzle, Symfony HttpClient, Buzz, or any other implementation at the edge.
Package shape
Use a package layout that separates public API from HTTP plumbing.
acme-php/
src/
AcmeClient.php
AcmeClientBuilder.php
Exceptions/
AcmeException.php
ApiException.php
AuthenticationException.php
RateLimitException.php
TransportException.php
Http/
ApiRequest.php
ApiResponse.php
Psr18Transport.php
RetryPolicy.php
RetryingTransport.php
Sleeper.php
Transport.php
Resources/
CustomersResource.php
Value/
Customer.php
tests/
Fakes/
FakeTransport.php
CustomersResourceTest.php
composer.json
Runtime dependencies:
{
"require": {
"php": "^8.2",
"psr/http-client": "^1.0",
"psr/http-factory": "^1.0",
"psr/http-message": "^1.0 || ^2.0",
"psr/log": "^3.0"
}
}
Do not require Guzzle as the SDK transport unless you want every consumer to inherit that choice. If you want a convenient default, put it in a separate integration package or document an install command:
composer require acme/acme-php guzzlehttp/guzzle nyholm/psr7
Public client
The public client should be small and stable.
Usage:
declare(strict_types=1);
use Acme\Sdk\AcmeClient;
use GuzzleHttp\Client as GuzzleClient;
use Nyholm\Psr7\Factory\Psr17Factory;
$psr17 = new Psr17Factory();
$client = AcmeClient::builder()
->withApiKey($_ENV['ACME_API_KEY'])
->withBaseUri('https://api.acme.test')
->withHttpClient(new GuzzleClient())
->withRequestFactory($psr17)
->withStreamFactory($psr17)
->build();
$customer = $client->customers()->create([
'email' => 'ada@example.com',
'name' => 'Ada Lovelace',
]);
Implementation:
declare(strict_types=1);
namespace Acme\Sdk;
use Acme\Sdk\Http\Transport;
use Acme\Sdk\Resources\CustomersResource;
final readonly class AcmeClient
{
public function __construct(private Transport $transport) {}
public static function builder(): AcmeClientBuilder
{
return new AcmeClientBuilder();
}
public function customers(): CustomersResource
{
return new CustomersResource($this->transport);
}
}
The public class exposes resource groups. It does not know how PSR-7 streams are made, how retries sleep, or how Guzzle is configured.
Builder
The builder keeps setup readable without turning the main client into a bag of optional dependencies.
declare(strict_types=1);
namespace Acme\Sdk;
use Acme\Sdk\Http\Psr18Transport;
use Acme\Sdk\Http\RetryPolicy;
use Acme\Sdk\Http\RetryingTransport;
use Acme\Sdk\Http\Sleeper;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
final class AcmeClientBuilder
{
private ?string $apiKey = null;
private string $baseUri = 'https://api.acme.com';
private ?ClientInterface $httpClient = null;
private ?RequestFactoryInterface $requestFactory = null;
private ?StreamFactoryInterface $streamFactory = null;
private RetryPolicy $retryPolicy;
private LoggerInterface $logger;
public function __construct()
{
$this->retryPolicy = RetryPolicy::conservative();
$this->logger = new NullLogger();
}
public function withApiKey(string $apiKey): self
{
$clone = clone $this;
$clone->apiKey = $apiKey;
return $clone;
}
public function withBaseUri(string $baseUri): self
{
$clone = clone $this;
$clone->baseUri = rtrim($baseUri, '/');
return $clone;
}
public function withHttpClient(ClientInterface $httpClient): self
{
$clone = clone $this;
$clone->httpClient = $httpClient;
return $clone;
}
public function withRequestFactory(RequestFactoryInterface $requestFactory): self
{
$clone = clone $this;
$clone->requestFactory = $requestFactory;
return $clone;
}
public function withStreamFactory(StreamFactoryInterface $streamFactory): self
{
$clone = clone $this;
$clone->streamFactory = $streamFactory;
return $clone;
}
public function withRetryPolicy(RetryPolicy $retryPolicy): self
{
$clone = clone $this;
$clone->retryPolicy = $retryPolicy;
return $clone;
}
public function withLogger(LoggerInterface $logger): self
{
$clone = clone $this;
$clone->logger = $logger;
return $clone;
}
public function build(): AcmeClient
{
if ($this->apiKey === null || $this->apiKey === '') {
throw new \LogicException('An Acme API key is required.');
}
if ($this->httpClient === null || $this->requestFactory === null || $this->streamFactory === null) {
throw new \LogicException('A PSR-18 HTTP client, PSR-17 request factory, and PSR-17 stream factory are required.');
}
$transport = new Psr18Transport(
httpClient: $this->httpClient,
requestFactory: $this->requestFactory,
streamFactory: $this->streamFactory,
baseUri: $this->baseUri,
apiKey: $this->apiKey,
);
return new AcmeClient(new RetryingTransport(
next: $transport,
policy: $this->retryPolicy,
sleeper: Sleeper::native(),
logger: $this->logger,
));
}
}
The builder is immutable. That keeps this safe:
$base = AcmeClient::builder()
->withHttpClient($httpClient)
->withRequestFactory($factory)
->withStreamFactory($factory);
$tenantA = $base->withApiKey('key_a')->build();
$tenantB = $base->withApiKey('key_b')->build();
No shared mutable API key leaks between clients.
SDK request and response objects
Create a narrow SDK-level HTTP contract. Resource classes should not assemble PSR-7 requests directly.
declare(strict_types=1);
namespace Acme\Sdk\Http;
final readonly class ApiRequest
{
/**
* @param array<string, string> $headers
* @param array<string, scalar|null> $query
* @param array<string, mixed>|null $json
*/
public function __construct(
public string $method,
public string $path,
public array $headers = [],
public array $query = [],
public ?array $json = null,
public ?string $idempotencyKey = null,
) {}
public function isRetryableByDefault(): bool
{
return in_array($this->method, ['GET', 'HEAD', 'OPTIONS', 'DELETE'], true)
|| $this->idempotencyKey !== null;
}
}
Response:
declare(strict_types=1);
namespace Acme\Sdk\Http;
final readonly class ApiResponse
{
/**
* @param array<string, list<string>> $headers
* @param array<string, mixed>|list<mixed>|null $json
*/
public function __construct(
public int $statusCode,
public array $headers,
public ?array $json,
public string $body,
) {}
public function headerLine(string $name): string
{
foreach ($this->headers as $header => $values) {
if (strcasecmp($header, $name) === 0) {
return implode(', ', $values);
}
}
return '';
}
/**
* @return array<string, mixed>
*/
public function jsonData(): array
{
if (! is_array($this->json) || array_is_list($this->json)) {
throw new \UnexpectedValueException('Expected a JSON object response.');
}
return $this->json;
}
}
Transport interface:
declare(strict_types=1);
namespace Acme\Sdk\Http;
interface Transport
{
public function send(ApiRequest $request): ApiResponse;
}
This internal interface is easier to fake than PSR-18 because it works at your SDK boundary.
[IMAGE: Supporting visual 1 for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes, showing Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes decisions, examples, and PHP, SDK, PSR-18. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes building-php-sdk-http-client-abstraction-retries-test-fakes visual 1]
[IMAGE: Supporting visual 1 for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes, showing Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes decisions, examples, and PHP, SDK, PSR-18. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes building-php-sdk-http-client-abstraction-retries-test-fakes visual 1]
PSR-18 transport adapter
PSR-18 says a client sends a PSR-7 request and returns a PSR-7 response. It also says 4xx and 5xx responses are not transport exceptions. Your SDK must inspect status codes itself.
declare(strict_types=1);
namespace Acme\Sdk\Http;
use Acme\Sdk\Exceptions\TransportException;
use Psr\Http\Client\ClientExceptionInterface;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestFactoryInterface;
use Psr\Http\Message\StreamFactoryInterface;
final readonly class Psr18Transport implements Transport
{
public function __construct(
private ClientInterface $httpClient,
private RequestFactoryInterface $requestFactory,
private StreamFactoryInterface $streamFactory,
private string $baseUri,
private string $apiKey,
) {}
public function send(ApiRequest $request): ApiResponse
{
$psrRequest = $this->requestFactory
->createRequest($request->method, $this->uriFor($request))
->withHeader('Accept', 'application/json')
->withHeader('User-Agent', 'acme-php/1.0')
->withHeader('Authorization', 'Bearer '.$this->apiKey);
foreach ($request->headers as $name => $value) {
$psrRequest = $psrRequest->withHeader($name, $value);
}
if ($request->idempotencyKey !== null) {
$psrRequest = $psrRequest->withHeader('Idempotency-Key', $request->idempotencyKey);
}
if ($request->json !== null) {
$body = json_encode($request->json, JSON_THROW_ON_ERROR);
$psrRequest = $psrRequest
->withHeader('Content-Type', 'application/json')
->withBody($this->streamFactory->createStream($body));
}
try {
$response = $this->httpClient->sendRequest($psrRequest);
} catch (ClientExceptionInterface $exception) {
throw TransportException::fromClientException($exception);
}
$body = (string) $response->getBody();
return new ApiResponse(
statusCode: $response->getStatusCode(),
headers: $response->getHeaders(),
json: $body === '' ? null : json_decode($body, true, flags: JSON_THROW_ON_ERROR),
body: $body,
);
}
private function uriFor(ApiRequest $request): string
{
$uri = $this->baseUri.'/'.ltrim($request->path, '/');
if ($request->query === []) {
return $uri;
}
return $uri.'?'.http_build_query($request->query, '', '&', PHP_QUERY_RFC3986);
}
}
Keep http_errors disabled if the consumer uses Guzzle directly in a non-PSR-18 path. With PSR-18, HTTP error statuses should still come back as responses.
Transport exception:
declare(strict_types=1);
namespace Acme\Sdk\Exceptions;
use Psr\Http\Client\ClientExceptionInterface;
final class TransportException extends AcmeException
{
public static function fromClientException(ClientExceptionInterface $exception): self
{
return new self(
message: 'The Acme API request could not be sent.',
previous: $exception,
);
}
}
Map API errors once
Do not make every resource method check 401, 404, 422, 429, and 500.
declare(strict_types=1);
namespace Acme\Sdk\Exceptions;
use Acme\Sdk\Http\ApiResponse;
class AcmeException extends \RuntimeException {}
class ApiException extends AcmeException
{
/**
* @param array<string, mixed>|list<mixed>|null $payload
*/
public function __construct(
public readonly int $statusCode,
public readonly ?array $payload,
string $message,
) {
parent::__construct($message);
}
public static function fromResponse(ApiResponse $response): self
{
$message = is_array($response->json) && is_string($response->json['message'] ?? null)
? $response->json['message']
: 'The Acme API returned HTTP '.$response->statusCode.'.';
return match ($response->statusCode) {
401, 403 => new AuthenticationException($response->statusCode, $response->json, $message),
429 => new RateLimitException($response->statusCode, $response->json, $message, $response->headerLine('Retry-After')),
default => new self($response->statusCode, $response->json, $message),
};
}
}
final class AuthenticationException extends ApiException {}
final class RateLimitException extends ApiException
{
public function __construct(
int $statusCode,
?array $payload,
string $message,
public readonly string $retryAfter,
) {
parent::__construct($statusCode, $payload, $message);
}
}
Then one helper can enforce success:
declare(strict_types=1);
namespace Acme\Sdk\Http;
use Acme\Sdk\Exceptions\ApiException;
final class ResponseValidator
{
public static function expect(int $statusCode, ApiResponse $response): ApiResponse
{
if ($response->statusCode === $statusCode) {
return $response;
}
throw ApiException::fromResponse($response);
}
}
Resource class
Resource methods should read like API operations, not like HTTP plumbing.
declare(strict_types=1);
namespace Acme\Sdk\Resources;
use Acme\Sdk\Http\ApiRequest;
use Acme\Sdk\Http\ResponseValidator;
use Acme\Sdk\Http\Transport;
use Acme\Sdk\Value\Customer;
final readonly class CustomersResource
{
public function __construct(private Transport $transport) {}
/**
* @param array{email: string, name: string} $payload
*/
public function create(array $payload, ?string $idempotencyKey = null): Customer
{
$response = $this->transport->send(new ApiRequest(
method: 'POST',
path: '/v1/customers',
json: $payload,
idempotencyKey: $idempotencyKey,
));
$response = ResponseValidator::expect(201, $response);
return Customer::fromArray($response->jsonData());
}
public function get(string $customerId): Customer
{
$response = $this->transport->send(new ApiRequest(
method: 'GET',
path: '/v1/customers/'.rawurlencode($customerId),
));
$response = ResponseValidator::expect(200, $response);
return Customer::fromArray($response->jsonData());
}
}
The strict jsonData() accessor keeps resource code from guessing whether a JSON body exists.
Value object:
declare(strict_types=1);
namespace Acme\Sdk\Value;
final readonly class Customer
{
public function __construct(
public string $id,
public string $email,
public string $name,
) {}
/**
* @param array<string, mixed> $data
*/
public static function fromArray(array $data): self
{
return new self(
id: self::string($data, 'id'),
email: self::string($data, 'email'),
name: self::string($data, 'name'),
);
}
/**
* @param array<string, mixed> $data
*/
private static function string(array $data, string $key): string
{
if (! isset($data[$key]) || ! is_string($data[$key])) {
throw new \UnexpectedValueException('Expected string field: '.$key);
}
return $data[$key];
}
}
SDKs should validate provider responses. A changed API field should fail loudly in one place instead of becoming a TypeError five calls later.
Retry policy
Retries belong in a decorator around the transport.
Default rules:
- Retry network failures when the operation is safe to retry.
- Retry
408,429,500,502,503, and504. - Honor
Retry-Afterwhen present. - Use exponential backoff with jitter.
- Do not retry non-idempotent
POSTrequests unless the operation has an idempotency key. - Keep retries bounded.
declare(strict_types=1);
namespace Acme\Sdk\Http;
final readonly class RetryPolicy
{
/**
* @param list<int> $statusCodes
*/
public function __construct(
public int $maxAttempts,
public int $baseDelayMilliseconds,
public int $maxDelayMilliseconds,
public array $statusCodes,
) {}
public static function conservative(): self
{
return new self(
maxAttempts: 3,
baseDelayMilliseconds: 200,
maxDelayMilliseconds: 2000,
statusCodes: [408, 429, 500, 502, 503, 504],
);
}
public function shouldRetryResponse(ApiRequest $request, ApiResponse $response, int $attempt): bool
{
return $attempt < $this->maxAttempts
&& $request->isRetryableByDefault()
&& in_array($response->statusCode, $this->statusCodes, true);
}
public function delayMilliseconds(ApiResponse $response, int $attempt): int
{
$retryAfter = $this->retryAfterMilliseconds($response);
if ($retryAfter !== null) {
return min($retryAfter, $this->maxDelayMilliseconds);
}
$backoff = $this->baseDelayMilliseconds * (2 ** max(0, $attempt - 1));
$jitter = random_int(0, $this->baseDelayMilliseconds);
return min($backoff + $jitter, $this->maxDelayMilliseconds);
}
private function retryAfterMilliseconds(ApiResponse $response): ?int
{
$value = trim($response->headerLine('Retry-After'));
if ($value === '') {
return null;
}
if (ctype_digit($value)) {
return ((int) $value) * 1000;
}
$timestamp = strtotime($value);
if ($timestamp === false) {
return null;
}
return max(0, ($timestamp - time()) * 1000);
}
}
RFC 9110 allows Retry-After to be either an HTTP date or a delay in seconds. Support both.
Retry decorator
Add a Sleeper abstraction so tests do not actually sleep.
declare(strict_types=1);
namespace Acme\Sdk\Http;
interface Sleeper
{
public function sleepMilliseconds(int $milliseconds): void;
public static function native(): self
{
return new class implements Sleeper {
public function sleepMilliseconds(int $milliseconds): void
{
usleep($milliseconds * 1000);
}
};
}
}
Decorator:
declare(strict_types=1);
namespace Acme\Sdk\Http;
use Acme\Sdk\Exceptions\TransportException;
use Psr\Log\LoggerInterface;
final readonly class RetryingTransport implements Transport
{
public function __construct(
private Transport $next,
private RetryPolicy $policy,
private Sleeper $sleeper,
private LoggerInterface $logger,
) {}
public function send(ApiRequest $request): ApiResponse
{
$attempt = 1;
while (true) {
try {
$response = $this->next->send($request);
} catch (TransportException $exception) {
if ($attempt >= $this->policy->maxAttempts || ! $request->isRetryableByDefault()) {
throw $exception;
}
$this->sleepBeforeRetry($attempt, null);
$attempt++;
continue;
}
if (! $this->policy->shouldRetryResponse($request, $response, $attempt)) {
return $response;
}
$this->sleepBeforeRetry($attempt, $response);
$attempt++;
}
}
private function sleepBeforeRetry(int $attempt, ?ApiResponse $response): void
{
$milliseconds = $response === null
? $this->policy->baseDelayMilliseconds
: $this->policy->delayMilliseconds($response, $attempt);
$this->logger->warning('Acme API request scheduled for retry.', [
'attempt' => $attempt,
'delay_ms' => $milliseconds,
'status' => $response?->statusCode,
]);
$this->sleeper->sleepMilliseconds($milliseconds);
}
}
This is middleware in the architectural sense, but it is not Guzzle middleware. It is a transport decorator that works with any PSR-18 client underneath.
Test fake
Most SDK tests should not hit a real API or mock Guzzle. Fake the SDK transport and assert the request your SDK built.
declare(strict_types=1);
namespace Acme\Sdk\Tests\Fakes;
use Acme\Sdk\Http\ApiRequest;
use Acme\Sdk\Http\ApiResponse;
use Acme\Sdk\Http\Transport;
final class FakeTransport implements Transport
{
/** @var list<ApiRequest> */
private array $requests = [];
/** @var list<ApiResponse> */
private array $responses = [];
public function queue(ApiResponse $response): void
{
$this->responses[] = $response;
}
public function send(ApiRequest $request): ApiResponse
{
$this->requests[] = $request;
$response = array_shift($this->responses);
if (! $response instanceof ApiResponse) {
throw new \RuntimeException('No fake response queued.');
}
return $response;
}
/**
* @return list<ApiRequest>
*/
public function requests(): array
{
return $this->requests;
}
}
Resource test:
declare(strict_types=1);
use Acme\Sdk\AcmeClient;
use Acme\Sdk\Http\ApiResponse;
use Acme\Sdk\Tests\Fakes\FakeTransport;
use PHPUnit\Framework\TestCase;
final class CustomersResourceTest extends TestCase
{
public function test_it_creates_a_customer(): void
{
$transport = new FakeTransport();
$transport->queue(new ApiResponse(
statusCode: 201,
headers: ['Content-Type' => ['application/json']],
json: [
'id' => 'cus_123',
'email' => 'ada@example.com',
'name' => 'Ada Lovelace',
],
body: '{"id":"cus_123","email":"ada@example.com","name":"Ada Lovelace"}',
));
$client = new AcmeClient($transport);
$customer = $client->customers()->create([
'email' => 'ada@example.com',
'name' => 'Ada Lovelace',
], idempotencyKey: 'create-customer-1');
self::assertSame('cus_123', $customer->id);
$request = $transport->requests()[0];
self::assertSame('POST', $request->method);
self::assertSame('/v1/customers', $request->path);
self::assertSame('create-customer-1', $request->idempotencyKey);
self::assertSame('ada@example.com', $request->json['email']);
}
}
Retry test:
declare(strict_types=1);
use Acme\Sdk\Http\ApiRequest;
use Acme\Sdk\Http\ApiResponse;
use Acme\Sdk\Http\RetryPolicy;
use Acme\Sdk\Http\RetryingTransport;
use Acme\Sdk\Http\Sleeper;
use Acme\Sdk\Tests\Fakes\FakeTransport;
use PHPUnit\Framework\TestCase;
use Psr\Log\NullLogger;
final class RetryingTransportTest extends TestCase
{
public function test_it_retries_a_retryable_response(): void
{
$fake = new FakeTransport();
$fake->queue(new ApiResponse(503, [], ['message' => 'maintenance'], '{}'));
$fake->queue(new ApiResponse(200, [], ['id' => 'cus_123'], '{"id":"cus_123"}'));
$sleeper = new class implements Sleeper {
/** @var list<int> */
public array $sleeps = [];
public function sleepMilliseconds(int $milliseconds): void
{
$this->sleeps[] = $milliseconds;
}
};
$transport = new RetryingTransport(
next: $fake,
policy: new RetryPolicy(3, 100, 100, [503]),
sleeper: $sleeper,
logger: new NullLogger(),
);
$response = $transport->send(new ApiRequest('GET', '/v1/customers/cus_123'));
self::assertSame(200, $response->statusCode);
self::assertCount(2, $fake->requests());
self::assertSame([100], $sleeper->sleeps);
}
}
This test is fast because it does not use the network and does not sleep.
Real HTTP integration test
Keep a small number of tests for the PSR-18 adapter. These should prove request construction, headers, JSON body encoding, response parsing, and transport exception wrapping.
[IMAGE: Supporting visual 2 for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes, showing Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes decisions, examples, and PHP, SDK, PSR-18. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes building-php-sdk-http-client-abstraction-retries-test-fakes visual 2]
With Guzzle, use its mock handler in adapter tests only:
declare(strict_types=1);
use Acme\Sdk\Http\ApiRequest;
use Acme\Sdk\Http\Psr18Transport;
use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\TestCase;
final class Psr18TransportTest extends TestCase
{
public function test_it_sends_json_with_authentication(): void
{
$mock = new MockHandler([
new Response(200, ['Content-Type' => 'application/json'], '{"ok":true}'),
]);
$httpClient = new Client(['handler' => HandlerStack::create($mock)]);
$factory = new Psr17Factory();
$transport = new Psr18Transport(
httpClient: $httpClient,
requestFactory: $factory,
streamFactory: $factory,
baseUri: 'https://api.acme.test',
apiKey: 'secret',
);
$response = $transport->send(new ApiRequest(
method: 'POST',
path: '/v1/customers',
json: ['email' => 'ada@example.com'],
));
self::assertSame(200, $response->statusCode);
self::assertSame(['ok' => true], $response->json);
}
}
Most resource tests should still use your fake transport. Adapter tests can use a concrete HTTP client because the adapter is the only place that cares about the concrete client.
[IMAGE: Supporting visual 2 for Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes, showing Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes decisions, examples, and PHP, SDK, PSR-18. Alt: Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes building-php-sdk-http-client-abstraction-retries-test-fakes visual 2]
Pagination and fluent helpers
Add fluent helpers only when they remove real call-site noise.
Good:
$customers = $client->customers()
->list()
->withEmail('ada@example.com')
->withLimit(50)
->send();
Weak:
$customers = $client
->v1()
->resources()
->customers()
->operations()
->list()
->execute();
A fluent API is useful when it names real options and prevents invalid combinations. It is not useful when it just mirrors the internal class tree.
For pagination, prefer an iterator:
foreach ($client->customers()->all(['status' => 'active']) as $customer) {
sync_customer($customer);
}
The SDK can hide cursor handling while still letting users break early.
What not to expose
Do not expose these as part of the stable public API unless you must:
- Guzzle request options.
- Raw PSR-7 requests in every resource method.
- The remote API's full error payload shape as required constructor input.
- Mutable global configuration.
- Static API keys.
- Sleep calls that cannot be faked.
- Retry loops inside every resource class.
- Public arrays where a response value object would be clearer.
You can still offer an escape hatch:
$client->transport()->send(new ApiRequest('GET', '/v1/raw-endpoint'));
But keep the normal path stable and typed.
Release checklist
Before tagging v1.0.0:
- Public client API is small enough to support for years.
composer.jsondepends on PSR interfaces, not one concrete HTTP implementation.- HTTP statuses are mapped to stable SDK exceptions.
- PSR-18 transport treats 4xx and 5xx as responses.
- Retry policy is bounded and idempotency-aware.
Retry-Aftersupports seconds and HTTP dates.- Tests use fakes for resources and concrete clients only for adapter coverage.
- JSON encoding and decoding use
JSON_THROW_ON_ERROR. - Every network path can be logged without leaking secrets.
- README shows installation, client construction, common calls, errors, retries, and testing.
An SDK is a contract. The useful work is making the contract boring for consumers and strict for maintainers.
FAQ
What is Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes?
Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes is a practical apis topic that should be evaluated through implementation scope, production risk, testing, documentation, and long-term maintainability.
When should a team use Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes?
Use Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes when it solves a real project constraint, improves clarity, or reduces operational risk. Avoid it when it only adds novelty or hides behavior from future maintainers.
What is the biggest risk with Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes?
The biggest risk is copying a pattern without its context. Production systems need clear boundaries, rollback options, tests, and observability before a technique becomes dependable.
How do you test Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes?
Test the smallest unit that owns the behavior, then add integration coverage for the path users or systems actually rely on. Include failure cases, configuration differences, and regression checks.
How does Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes affect SEO and AI search visibility?
It improves visibility when the article gives a direct answer, expert context, structured headings, internal links, trustworthy references, and FAQ content that matches the visible page.
Conclusion
Building a PHP SDK: HTTP Client Abstraction, Retries & Test Fakes is worth doing when the implementation improves clarity, reliability, or delivery speed. It is not worth doing when it hides ownership, increases operational risk, or makes the system harder to explain.
Use the framework above as a review checklist. Then connect this topic to the rest of the project documentation so readers can move from concept to implementation without losing context.