michaelalexeevweb / openapi-php-dto-generator
Generate PHP DTOs from OpenAPI and validate incoming HTTP requests against OpenAPI schema.
Package info
github.com/michaelalexeevweb/openapi-php-dto-generator
pkg:composer/michaelalexeevweb/openapi-php-dto-generator
Fund package maintenance!
Requires
- php: ^8.3
- symfony/console: ^7.4
- symfony/http-foundation: ^7.4
- symfony/mime: ^7.4
- symfony/yaml: ^7.4
- twig/twig: ^3.0
Requires (Dev)
- ergebnis/phpstan-rules: ^2.13
- friendsofphp/php-cs-fixer: ^3.95
- illuminate/config: ^11 || ^12
- illuminate/container: ^11 || ^12
- illuminate/events: ^11 || ^12
- illuminate/filesystem: ^11 || ^12
- illuminate/http: ^11 || ^12
- illuminate/routing: ^11 || ^12
- illuminate/translation: ^11 || ^12
- illuminate/validation: ^11 || ^12
- kubawerlos/php-cs-fixer-custom-fixers: ^3.37
- nyholm/psr7: ^1.8
- phpdocumentor/reflection-docblock: ^5.4
- phpstan/phpstan: ^2.1
- phpstan/phpstan-strict-rules: ^2.0
- phpunit/phpunit: ^10.5
- slevomat/coding-standard: ^8.29
- spatie/laravel-data: ^4.23
- squizlabs/php_codesniffer: ^4.0
- symfony/property-access: ^7.4
- symfony/property-info: ^7.4
- symfony/psr-http-message-bridge: ^7.4
- symfony/serializer: ^7.4
- symfony/validator: ^7.4
- yiisoft/hydrator: ^1.6
- yiisoft/hydrator-validator: ^2.0
- yiisoft/input-http: ^1.0
- yiisoft/request-provider: ^1.3
- yiisoft/validator: ^2.6
Suggests
- ext-intl: Required by yiisoft/validator's Date, DateTime and Time rules, which yii3 mode emits for temporal formats.
- spatie/laravel-data: To use the generated Data classes in laravel-data mode (--attributes=laravel-data).
- symfony/psr-http-message-bridge: To deserialize PSR-7 ServerRequest objects via DtoDeserializerPsr7 (non-Symfony stacks: Slim, Mezzio, Laminas, Yii3, …).
- symfony/serializer: To (de)serialize Symfony attribute-mode DTOs via the Symfony serializer.
- symfony/validator: To use the generated DTOs in Symfony attribute mode (--attributes=symfony).
- yiisoft/input-http: To have yii3 hydrate the generated inputs from the request (--attributes=yii3).
- yiisoft/validator: To use the generated inputs in yii3 mode (--attributes=yii3).
This package is auto-updated.
Last update: 2026-08-21 11:34:07 UTC
README
Your OpenAPI document, enforced by the PHP it generates.
Point it at an OpenAPI 3.0 / 3.1 spec. Get immutable, strictly-typed PHP 8.3 DTOs whose generated code
enforces the schema, not just the types — oneOf, minimum, pattern, format,
unevaluatedProperties and the rest of a broad, tested vocabulary — for Symfony, Laravel,
spatie/laravel-data, Yii3, or standalone.
Generate DTOs from OpenAPI, deserialize a Symfony Request or any PSR-7 request straight into them,
validate incoming HTTP requests against the OpenAPI schema, and normalize back to arrays or JSON — one
package, and no spec parsing at runtime.
- In: an OpenAPI 3.0 / 3.1 document, YAML or JSON.
- Out: one PHP class per schema — from
components.schemasand from each operation's body, query and path parameters. - Use it for: server-side request DTOs, PATCH-safe presence, response normalization.
- Not for: generating an API client or SDK — see what it does not do.
- Start with:
runtimemode, the default. Reach for a framework mode only when you want that framework's own validation output.
composer require michaelalexeevweb/openapi-php-dto-generator:^2.15.2
60 seconds
This document:
components: schemas: UserPostRequest: type: object required: [email] properties: email: {type: string, format: email} age: {type: integer, minimum: 18} nickname: {type: [string, 'null']}
Through this command:
php vendor/michaelalexeevweb/openapi-php-dto-generator/bin/console openapi:generate-dto \
--file=openapi.yaml --directory=src/Generated --namespace='App\Generated'
Becomes this class — an optional property defaults to a sentinel, not to null, which is what keeps
"absent" and "sent as null" apart:
final class UserPostRequest implements GeneratedDtoInterface, Stringable { public function __construct( private readonly string $email, private readonly int|UnsetValue|null $age = UnsetValue::UNSET, private readonly string|UnsetValue|null $nickname = UnsetValue::UNSET, ) { /* … */ } public function getEmail(): string { /* … */ } public function getAge(): ?int { /* … */ } public function getNickname(): ?string { /* … */ } public function isNicknameInRequest(): bool { /* … */ } // was the key sent at all? }
Which you use like this:
$dto = (new DtoDeserializer())->deserialize($request, UserPostRequest::class); $body = (new DtoNormalizer())->validateAndNormalizeToArray($responseDto);
And which answers like this — the messages below are the real output, not a paraphrase:
| request body | getNickname() |
isNicknameInRequest() |
|---|---|---|
{"email":"a@b.test"} |
null |
false — the key never came |
{"email":"a@b.test","nickname":null} |
null |
true — the client sent null on purpose |
{"email":"a@b.test","nickname":"neo"} |
"neo" |
true |
Same getter, different answer: that distinction is what a PATCH endpoint needs and what a plain ?string
cannot express. And when the document is not satisfied:
| request body | error |
|---|---|
{"age":30} |
Required parameter "email" not found in request. |
{"email":"nope","age":12} |
param "email" must match format emailparam "age" must be greater than or equal to 18 |
format: email and minimum: 18 are enforced by code the generator wrote, and both problems are
reported together rather than one at a time.
The presence accessor is named for its mode: isNicknameInRequest() in runtime, isNicknameProvided()
in symfony, laravel and yii3. laravel-data needs neither — there the property's own type is
string|Optional.
Add --attributes=symfony|laravel|laravel-data|yii3 to get the same enforcement in your framework's own
shape instead.
Every CLI option, and how to vendor the runtime services →
Why this one
Five PHP tools were downloaded and run on the same spec with the same payloads. Nothing below is quoted from anyone's README — every cell is a verdict the tool actually returned.
| enforced by the code it generates | minimum / maximum |
pattern |
format |
oneOf |
builds a typed object |
|---|---|---|---|---|---|
JanePHP open-api-3 7.13, validation: true |
❌ | ❌ | ❌ | ❌ | ✅ |
OpenAPI Generator 7.24 — php-symfony, php-dt, php-nextgen |
❌ | ❌ | ❌ | ❌ | ✅ |
maxbeckers/php-openapi-generator 0.1.6 |
❌ | ❌ | ❌ | ❌ | ✅ |
league/openapi-psr7-validator 0.24 |
✅ | ✅ | ✅¹ | ✅ | ❌ |
| this library | ✅ | ✅ | ✅ | ✅ | ✅ |
¹ everything except uri-template.
Every other generator in the set checks the type and whether the key is present, and stops there. In the whole set the OpenAPI vocabulary is enforced by exactly one tool — a runtime validator that generates no classes at all. This is the only one that does both.
On real payloads that means code: 5 against minimum: 10 is refused here and accepted by Jane; a
malformed uri-template is refused here and accepted by both Jane and league; and where league answers
Keyword validation failed: Data must match exactly one schema, this answers
param "code" must match format uuid.
Every payload, every verdict, the versions, and where we are behind →
Three things that only fall out of generating the checks
- Nothing is parsed at boot. The spec is compiled into a literal
constinside the generated class.leaguere-reads the YAML in every PHP process — 21.8 ms before it answers the first request. Here that cost does not exist. Performance → - PATCH is expressible. "Absent" and "sent as
null" stay different values — a sentinel, anOptionalmember, or an uninitialised typed property, depending on the mode. OpenAPI Generator makes every property nullable with= null, so the two collapse into one and a partial update cannot be written correctly. - An undiscriminated
anyOfstays honest. You get an interface plus one class per branch, and a warning at generation time saying it will not be hydrated. Others flatten the branches into a single class — where a cat carryingbarkpasses — or drop the property tomixed.
Fast, because the checks are emitted code
bin/benchmark, PHP 8.5 in the project container, opcache off, 20 000 iterations, mean of two runs:
| bind | validate | normalize | round trip | |
|---|---|---|---|---|
| runtime | 0.1232 ms | 0.1177 ms | 0.0178 ms | 0.2588 ms |
laravel (FormRequest) |
0.0037 ms | 1.7163 ms | 0.0032 ms | 1.7233 ms |
The generated Laravel interpreter — the part this library actually writes — is 1.9% of that Laravel
validate step; the millisecond is illuminate/validation walking the rule array.
Full numbers, and the benchmark to re-run them →
Five modes
All five enforce the same schema validation vocabulary — the keywords above hold in every one of them. What differs is everything around it: who validates, what the errors look like, what you install, and how much of the REQUEST the document still governs.
| Mode | What it emits | Needs | Errors arrive as |
|---|---|---|---|
| runtime (default) | immutable DTO + this library's validator / normalizer / deserializer | this package | one aggregated exception |
| symfony | plain DTO with #[Assert\*], #[SerializedName], #[Groups] |
symfony/validator + symfony/serializer |
ConstraintViolationList, 422 via #[MapRequestPayload] |
| laravel | plain DTO + a FormRequest carrying rules() |
nothing beyond the framework | the framework's own 422 error bag |
| laravel-data | one Data class per schema, Optional for presence |
spatie/laravel-data |
the framework's own 422 error bag |
| yii3 | one AbstractInput per schema, yiisoft/validator attributes |
yiisoft/validator + yiisoft/hydrator + yiisoft/input-http |
a Result your action reads |
Request binding is not the same in every mode, and that is the one difference worth knowing before you choose. A framework mode hands binding to its own serializer or hydrator, which has already decided what the payload is before any generated code runs:
| runtime | symfony | laravel | laravel-data | yii3 | |
|---|---|---|---|---|---|
parameter sources — path / query / header / cookie |
✅ | ❌ | ❌ | ❌ | body, query, path only |
style / explode / allowReserved / allowEmptyValue |
✅ | ❌ | ❌ | ❌ | ❌ |
multipart encoding |
✅ | ❌ | ❌ | ❌ | ❌ |
Rule of thumb. Not sure? Take runtime — it is the default, it needs no framework, and it is the only mode where the REQUEST itself follows the document. Take symfony or laravel when you want plain DTOs your framework owns and errors in the shape it already speaks. Take laravel-data or yii3 when your application already runs that package.
There are thirteen further divergences, all deliberate and each pinned by a test that names its cause. They are written down rather than left to be discovered: the support matrix gives the keyword-by-keyword answer per mode and lists what is not generated in any of them. It is derived from the parity test suites, so a row that stops being true fails a test.
Documentation
| what is in it | |
|---|---|
| How it compares | five tools downloaded and run on the same spec, same payloads |
| Support matrix | every keyword per mode, every divergence, what is out of scope |
| Performance | bind / validate / normalize per mode, measured, with the benchmark |
| Validation notes | where a careless reading of the spec and a correct one disagree |
| CLI reference | every option, vendoring the runtime, external $ref mapping |
| runtime · symfony · laravel · laravel-data · yii3 | one guide per mode: what it does, how to wire it, where it stops |
| CHANGELOG | every release, what it breaks, and what to do about it |
Requirements
PHP 8.3+ and the Symfony 7.4 components console, http-foundation, mime, yaml. Each mode's own
dependencies are in its guide.
What it does not do
It generates the server side: the classes an incoming request becomes, and the checks that request must pass. It does not generate an HTTP client or an SDK for calling someone else's API — if that is what you need, JanePHP and OpenAPI Generator do it and this does not.
Upgrading
composer update, then regenerate. Every release says what changed in the emitted code, what breaks and
what to do about it: CHANGELOG.md.
The one signature change to watch for is 2.12.0 → 2.13.0, and only if a class of your own implements
DtoDeserializerInterface — two methods gained optional parameters there.
License
MIT.