---
name: integrate-php-client
description: >
  Use the generated PHP client in a PHP 8 application. Covers Symfony
  HttpClient and Serializer dependencies via Composer, PSR-4 autoloading of
  the generated directory, instantiation with HttpClientInterface and
  baseUrl, typed model classes and backed enums, ApiResponse, ApiException
  handling, the generated SerializerFactory, and the --php-version /
  --namespace generation flags. Load when importing or using a generated
  php-mode client directory.
type: framework
library: openapi-client-generator
library_version: "3.0.0"
requires:
  - generate-client
sources:
  - "bazo/openapi-client-generator:src/modes/php/index.ts"
  - "bazo/openapi-client-generator:src/modes/php/helpers.ts"
  - "bazo/openapi-client-generator:src/modes/php/runtime.ts"
---

This skill builds on generate-client. Read it first for CLI usage.

# Integrate PHP Client

## Setup

Generate the client (unlike other modes, php outputs a directory of PSR-4 files):

```bash
openapi-client-generator api.json src/Api -n PetstoreClient -m php \
  --namespace "App\\Api\\Petstore" --php-version 8.2
```

This writes `src/Api/PetstoreClient/` containing `PetstoreClient.php`, `ApiResponse.php`, `ApiException.php`, `SerializerFactory.php`, and `Model/*.php`. `--namespace` defaults to the client name; `--php-version` (8.0–8.5) defaults to 8.1 and gates emitted features (backed enums and readonly need 8.1+, `readonly class` 8.2+, `#[\Deprecated]` 8.4+, `#[\NoDiscard]` and `Uri\Rfc3986` URL building 8.5+).

Add Composer dependencies:

```bash
composer require symfony/http-client symfony/serializer \
  symfony/property-info symfony/property-access phpdocumentor/reflection-docblock
```

`phpdocumentor/reflection-docblock` is required — without it, `Pet[]` collection properties silently degrade to arrays of plain arrays instead of hydrated model objects.

Map the namespace in `composer.json` (adjust to where you generated):

```json
{
    "autoload": {
        "psr-4": { "App\\Api\\Petstore\\": "src/Api/PetstoreClient/" }
    }
}
```

Instantiate the client:

```php
use App\Api\Petstore\PetstoreClient;
use Symfony\Component\HttpClient\HttpClient;

$api = new PetstoreClient(HttpClient::create(), 'https://api.example.com');
```

The constructor signature is:

```php
public function __construct(
    private readonly HttpClientInterface $client,
    private readonly string $baseUrl = self::DEFAULT_BASE_URL, // default only when the spec declares servers
    ?SerializerInterface $serializer = null,                   // defaults to SerializerFactory::create()
)
```

The third parameter is omitted when nothing in the client can use it — a spec whose operations
have no typed request body and no typed response body never serializes or deserializes anything,
so the client takes only `$client` and `$baseUrl`. Read the generated constructor rather than
assuming three parameters.

In a Symfony app, inject `HttpClientInterface` and register the client as a service instead of calling `HttpClient::create()`.

## Core Patterns

### Call a query operation

```php
$result = $api->listTasks(page: 1, limit: 10);
$result->data;    // TaskList — typed, hydrated model
$result->status;  // 200
$result->headers; // response headers (keys lower-cased by Symfony HttpClient)
```

Optional parameters default to `null`; use named arguments to skip earlier ones.

### Call a mutation operation

```php
use App\Api\Petstore\Model\CreateTaskRequest;
use App\Api\Petstore\Model\TaskStatus;

$result = $api->createTask(new CreateTaskRequest(
    title: 'Build feature',
    status: TaskStatus::Todo,
));
$result->data->id; // created task ID
```

Bodies are typed model classes; enum-typed fields take backed enum cases (PHP 8.1+ targets). A property written OpenAPI 3.1 style as `kind: { type: string, const: "system" }` counts as a one-value enum and gets its own one-case backed enum (`ConstSystemEventKind::System`); only a STRING `const` does, a boolean, integer or `null` `const` stays a plain `bool`/`int`/`mixed`. Unset optional properties are omitted from the request JSON.

### Handle API errors

```php
use App\Api\Petstore\ApiException;

try {
    $result = $api->getTask('nonexistent');
} catch (ApiException $e) {
    $e->statusCode;       // 404
    $e->body;             // raw response body
    $e->responseHeaders;
    $e->url;
}
```

Every non-success status throws `ApiException`; Symfony's own `HttpExceptionInterface` auto-throw is disabled by the generated code (`getContent(false)`).

### Immutable model updates (PHP 8.5 target)

Models are readonly; on a PHP 8.5 target use clone-with instead of mutation:

```php
$renamed = clone($task, ['title' => 'New title']);
```

### Wire names that are not PHP property names

A spec is free to name a field `a.b`, `2fa`, `first name` or `@type`. None of those can be a PHP
property name, so the generator folds each into a legal one — camel-casing across the characters
PHP cannot spell, prefixing a leading digit — and `#[SerializedName]` carries the original key, so
nothing changes on the wire:

```php
final class Thing
{
    public function __construct(
        #[SerializedName('a.b')]
        public readonly string $aB,
        #[SerializedName('2fa')]
        public readonly string $_2fa,
        #[SerializedName('first name')]
        public readonly string $firstName,
    ) {
    }
}
```

PHP property names may be keywords, so `class` and `function` are left alone. The one exception is
`this`, which PHP refuses as a promoted constructor property ("Cannot use $this as parameter"): it
becomes `$this_` with a `#[SerializedName('this')]`.

Query, header and multipart names are emitted as literal strings, so they are never folded. Two
field names that would fold onto the SAME property (`a.b` and `a-b`) are a generation error, not a
silent rename — rename one of them in the spec.

Enum VALUES fold the same way (`Male`, `male` and `MALE` all give `Male`), but they are NOT an
error: the duplicates are suffixed — `Male`, `Male_`, `MALE` — and every case keeps its own backing
value, so all three still round-trip. The swift and kotlin clients now deduplicate identically.
Suffixing is order-dependent, so it is stable for a given spec but a value inserted ahead of a
colliding one shifts the names after it; refer to a case through the generated identifier, never by
assuming a spelling.

### A schema with both `properties` and a `oneOf`

`{ type: object, properties: { album }, oneOf: [Song, Podcast] }` means "an object with `album`
that additionally satisfies one of the branches". The generator distributes the top-level
properties over every branch, so each branch gets its own model class carrying them alongside that
branch's own fields — `Model\SleeveOneOf1(string $album, string $track)` and
`Model\SleeveOneOf2(string $album, string $episode)`. Pass whichever one you mean; there is no
separate slot for the shared properties. All five modes distribute identically, so the parts on
the wire are the same from each. (A `type: "null"` branch of a nullable `anyOf` is left alone, and
a schema that also carries `allOf` or `enum` is not distributed — a schema carrying both already
reads inconsistently (the type-annotation resolvers test `allOf` before the union, the Swift and
Kotlin declaration generators test the union first), and distributing would only change which of
those two pre-existing readings wins, in some modes and not others. A sibling `allOf` is instead MERGED: the top-level properties become one more
`allOf` member, so they reach the generated type rather than being dropped.)

Two consequences worth knowing. The branch classes are **generated**
(`Model\<Union>OneOf1`, `Model\<Union>OneOf2`), so the original branch schemas stay declared but
are no longer referenced by the union — and if a spec of yours already used this shape, the class
you construct for a request body changes (`Model\NamedUpload` → `Model\SleeveOneOf1`). PHP has no
`case` construct and no sum type: a union is typed `mixed`, so you pass whichever branch model you
mean, and a union **response** arrives as the decoded associative array rather than as a branch
object — narrow it on the discriminator yourself. And because distribution reaches **response**
schemas too, the shared properties are now required in every branch: a response that omits one
fails to decode where it previously did not. That is what the spec asks for, but it is stricter
than before.

## File uploads (multipart)

An operation whose request body is `multipart/form-data` takes a generated model class where each `format: binary` field is typed `FilePart`:

```php
use App\Api\Petstore\FilePart;
use App\Api\Petstore\Model\UploadTaskAttachmentMultipartFormDataRequest;

$result = $api->uploadTaskAttachment('42', new UploadTaskAttachmentMultipartFormDataRequest(
    file: new FilePart(file_get_contents($path), 'invoice.pdf', 'application/pdf'),
    description: 'Q3 invoice',
));
```

`FilePart` is `__construct(string $contents, string $filename, ?string $contentType = null)`. The client builds a Symfony `FormDataPart` for you from `DataPart` (file) / plain-string (field) entries. Field encoding rules: scalar fields become one part; arrays of scalars become repeated parts under the same field name; objects and array-of-object fields become a single part carrying their JSON as a plain text field — no filename and no `Content-Type: application/json`, so a strict multipart parser reads it as a field whose value is the JSON text, exactly as the full and playwright clients send it (a plain string entry, not a `DataPart`); `null` fields are omitted entirely. A multipart body parameter that is itself nullable (`?Model\SomeRequest $body = null`) still sends a well-formed (empty) multipart body when omitted, not a bodyless request. A `oneOf`/`anyOf` body is typed `mixed` — pass whichever branch model you mean, and the client walks that object's own properties at request time, producing the same parts the other four modes send for the same branch. The walk is handed the branch's property → wire-name map, so a field the spec calls `file-name` is sent as `file-name`, not as the camel-cased `fileName` property. A union body's branches must each have a field set of their own: if any branch has none — a primitive, an array, or an object with no declared properties — the whole body falls back to sending no parts at all, in every mode alike. The same fallback applies to a union the Kotlin generator cannot express as a sealed class (most reachably when a schema named `<UnionName>Serializer` already exists, but also when the union carries a sibling `enum` or is an `anyOf` of one type plus `null`), because Kotlin then has no sum type to dispatch on and the five modes only stay in step by all sending nothing. A `oneOf`/`anyOf` **urlencoded** body dispatches on the branch in exactly the same way, sending that branch's own fields as `k=v` pairs — an array field as repeated keys, an object-valued field as one JSON-encoded value, and a property the shared model typed `FilePart` as its `contents`, exactly as the ordinary urlencoded path does (the same branch value produces the same bytes whichever way the body was declared) — and it takes the same fallback, with the same explanatory comment, only when the branches cannot be described. A SINGLE-variant `anyOf` (`anyOf: [$ref Only]`) is not a union at all: it is simply its branch, typed and sent as that object in every mode. A schema carrying BOTH top-level `properties` and an `allOf` means "an object with those properties that ALSO satisfies every member of the allOf": the generator folds the properties in as one more `allOf` member, so they appear in the generated type and on the wire alongside the composed base's fields (they used to be dropped from the type while the form walk still emitted a part for them). The folded properties go LAST, so they WIN any name they share with the base: a sibling `count: { type: string }` over a base's `count: { type: integer }` types the field `string`. That has always been this mode's reading; the full and playwright clients now agree, where before they emitted an intersection no payload could satisfy. A `nullable` field is treated exactly like an omitted one: a `nullable` scalar sends no part when it is `null` even if the spec marks it required, and a `nullable`-item array skips its `null` elements rather than sending an empty part for them. One PHP-only wrinkle, on both the union and the ordinary path: PHP has no separate map type, so an **empty** free-form map (`type: object` with `additionalProperties`) is JSON-encoded as `[]` where the other four modes send `{}`. A populated map is identical everywhere.

Form-urlencoded bodies (`application/x-www-form-urlencoded`) are built from the request model's fields into a urlencoded string — arrays become repeated keys, an object field is JSON-encoded into a single value, and a `format: binary` field is a plain `string`, not a `FilePart` (a urlencoded body cannot carry a file) — unless the same named schema also backs a MULTIPART body, in which case the one shared model types that property `FilePart` and the urlencoded operation sends the file's `contents` as the field value (one repeated key per element for an array); raw binary bodies (`application/octet-stream`, `image/*`, …) take a `FilePart` directly as the body and send its `contents`:

```php
$result = $api->uploadRawBlob(new FilePart(file_get_contents($path), 'blob.bin', 'application/octet-stream'));
```

A `text/*` body whose schema is a `string` is a plain `string` argument, sent verbatim under the
declared media type, never JSON-encoded.

Multipart support requires `symfony/mime` in addition to the packages listed above:

```bash
composer require symfony/mime
```

## Common Mistakes

### CRITICAL Missing serializer support packages

Wrong:

```bash
composer require symfony/http-client symfony/serializer
```

Correct:

```bash
composer require symfony/http-client symfony/serializer \
  symfony/property-info symfony/property-access phpdocumentor/reflection-docblock
```

The generated `SerializerFactory` wires `PhpDocExtractor` so constructor `@param Pet[]` docblocks drive collection hydration. Without `phpdocumentor/reflection-docblock`, nested arrays of models arrive as raw arrays and property reads fatal on type mismatch.

Source: src/modes/php/runtime.ts SerializerFactory

### HIGH A missing required key throws, even when the property is nullable

At `--php-version 8.1+` the generated `SerializerFactory` passes
`AbstractObjectNormalizer::REQUIRE_ALL_PROPERTIES => true` to `ObjectNormalizer`, so a key the
spec marks `required` must be PRESENT in the response, and a response that omits it raises
`Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException`.

Without the flag, Symfony fills `null` for any missing constructor argument whose type admits
null (`?string`, and `mixed` from a bare `const: null`), so PHP silently accepted payloads that
zod, Swift `Codable` and kotlinx.serialization all reject. The flag is what keeps the five modes
in step.

What does NOT change: a genuinely OPTIONAL property still hydrates when omitted (Symfony checks
`isDefaultValueAvailable()` first, and optional properties are emitted with `= null`), and an
explicit `null` for a required nullable property is still accepted. Only an ABSENT required key
throws.

If a server legitimately omits a field the spec marks `required`, that is a spec/server
disagreement — fix the spec (mark the property optional) rather than working around it in the
client, or the other four modes will keep rejecting the same payload.

The flag is deliberately absent at `--php-version 8.0`: it needs serializer >= 6.3, which needs
PHP >= 8.1, and the 8.0 target pairs with the older `AnnotationLoader` path.

Source: src/modes/php/runtime.ts SerializerFactory

### HIGH Wrong serializer version for a PHP 8.0 target

Wrong:

```bash
# --php-version 8.0 output with serializer 7.x
composer require symfony/serializer:^7.0
```

Correct:

```bash
# 8.0-target output uses AnnotationLoader, removed in serializer 7
composer require symfony/serializer:"^5.4|^6.0"
```

Code generated with `--php-version 8.0` imports `AnnotationLoader` and `Serializer\Annotation\SerializedName`, which serializer 7 removed. Targets 8.1+ use `AttributeLoader` and require serializer >= 6.4. Prefer `--php-version 8.1` or newer unless you are stuck on PHP 8.0.

Source: src/modes/php/runtime.ts serializerFactoryUses

### HIGH Editing the generated files directly

Wrong:

```php
// Adding a custom method inside the generated PetstoreClient.php
final class PetstoreClient
{
    // ...generated code...
    public function customMethod(): void { /* hand-written */ }
}
```

Correct:

```php
// Wrap or compose in your own class
final class PetstoreGateway
{
    public function __construct(private readonly PetstoreClient $api) {}

    public function customMethod(): void { /* hand-written */ }
}
```

The generated directory is regenerated from the spec; manual edits are overwritten. The generated client is `final` — compose, don't extend.

Source: maintainer interview

See also: generate-client/SKILL.md — CLI usage for regenerating the client
