{"id":36970179,"url":"https://github.com/larapie/data-transfer-object","last_synced_at":"2026-01-13T21:45:30.018Z","repository":{"id":57011758,"uuid":"177636567","full_name":"larapie/data-transfer-object","owner":"larapie","description":"Data transfer objects with validation through annotations","archived":false,"fork":true,"pushed_at":"2019-05-25T11:27:06.000Z","size":255,"stargazers_count":2,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-08-14T18:27:08.823Z","etag":null,"topics":["annotations","data-transfer-object","dto","php","validation"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"spatie/data-transfer-object","license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/larapie.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-03-25T17:50:26.000Z","updated_at":"2025-02-16T03:47:14.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/larapie/data-transfer-object","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/larapie/data-transfer-object","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/larapie%2Fdata-transfer-object","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/larapie%2Fdata-transfer-object/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/larapie%2Fdata-transfer-object/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/larapie%2Fdata-transfer-object/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/larapie","download_url":"https://codeload.github.com/larapie/data-transfer-object/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/larapie%2Fdata-transfer-object/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28401081,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-13T14:36:09.778Z","status":"ssl_error","status_checked_at":"2026-01-13T14:35:19.697Z","response_time":56,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["annotations","data-transfer-object","dto","php","validation"],"created_at":"2026-01-13T21:45:29.335Z","updated_at":"2026-01-13T21:45:30.009Z","avatar_url":"https://github.com/larapie.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Data transfer objects with validation through annotations\n\n[![Latest Stable Version](https://poser.pugx.org/larapie/data-transfer-object/v/stable)](https://packagist.org/packages/larapie/data-transfer-object)\n[![Build Status](https://travis-ci.org/larapie/data-transfer-object.svg?branch=master)](https://travis-ci.org/larapie/data-transfer-object)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/larapie/data-transfer-object/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/larapie/data-transfer-object/?branch=master)\n[![Code Coverage](https://scrutinizer-ci.com/g/larapie/data-transfer-object/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/larapie/data-transfer-object/?branch=master)\n[![StyleCI](https://github.styleci.io/repos/177636567/shield?branch=master)](https://github.styleci.io/repos/177636567)\n[![Total Downloads](https://poser.pugx.org/larapie/data-transfer-object/downloads)](https://packagist.org/packages/larapie/data-transfer-object)\n\n## Note\nEven though most of the codebase has been rewritten entirely. This project was originally forked from (https://github.com/spatie/data-transfer-object). The base repository is still maintained by spatie (https://github.com/spatie). Our goal is to increase the performance (mostly through caching of the reflection properties) and improve this package with additional features (see more below).\n\n#### Improvements:\n- Improved immutability.\n\n- Reflection property \u0026 annotation caching (for improved performance).\n\n- Fully qualified name resolving.\n\n- Immutable properties (through annotations).\n\n- Validation (through annotations).\n\n- Overriding \u0026 adding properties.\n\n- Optional property support.\n\n- Annotation/validation inheritance.\n\n## Installation\n\nYou can install the package via composer:\n\n```bash\ncomposer require larapie/data-transfer-object\n```\n\n## Have you ever…\n\n… worked with an array of data, retrieved from a request, a CSV file or a JSON API; and wondered what was in it?\n\nHere's an example:\n\n```php\npublic function handleRequest(array $dataFromRequest)\n{\n    $dataFromRequest[/* what to do now?? */];\n}\n```\n\nThe goal of this package is to structure \"unstructured data\", which is normally stored in associative arrays.\nBy structuring this data into an object, we gain several advantages:\n\n- We're able to type hint data transfer objects, instead of just calling them `array`.\n- By making all properties on our objects typeable, we're sure that their values are never something we didn't expect.\n- Because of typed properties, we can statically analyze them and have auto completion.\n\nLet's look at the example of a JSON API call:\n\n```php\n$post = $api-\u003eget('posts', 1); \n\n[\n    'title' =\u003e '…',\n    'body' =\u003e '…',\n    'author_id' =\u003e '…',\n]\n```\n\nWorking with this array is difficult, as we'll always have to refer to the documentation to know what's exactly in it. \nThis package allows you to create data transfer object definitions, classes, which will represent the data in a structured way.\n\nWe did our best to keep the syntax and overhead as little as possible:\n\n```php\nclass PostData extends DataTransferObject\n{\n    /** @var string */\n    public $title;\n    \n    /** @var string */\n    public $body;\n    \n    /** @var \\Author */\n    public $author;\n}\n```\n\nAn object of `PostData` can from now on be constructed like so:\n\n```php\n$postData = new PostData([\n    'title' =\u003e '…',\n    'body' =\u003e '…',\n    'author_id' =\u003e '…',\n]);\n```\n\nNow you can use this data in a structured way:\n\n```php\n$postData-\u003etitle;\n$postData-\u003ebody;\n$postData-\u003eauthor_id;\n```\n\nIt's, of course, possible to add static constructors to `PostData`:\n\n```php\nclass PostData extends DataTransferObject\n{\n    // …\n    \n    public static function fromRequest(Request $request): self\n    {\n        return new self([\n            'title' =\u003e $request-\u003eget('title'),\n            'body' =\u003e $request-\u003eget('body'),\n            'author' =\u003e Author::find($request-\u003eget('author_id')),\n        ]);\n    }\n}\n```\n\nBy adding doc blocks to our properties, their values will be validated against the given type; \nand a `TypeError` will be thrown if the value doesn't comply with the given type.\n\nHere are the possible ways of declaring types:\n\n```php\nclass PostData extends DataTransferObject\n{\n    /**\n     * Built in types: \n     *\n     * @var string \n     */\n    public $property;\n    \n    /**\n     * Classes with their FQCN: \n     *\n     * @var \\App\\Models\\Author\n     */\n    public $property;\n    \n    /**\n     * Lists of types: \n     *\n     * @var \\App\\Models\\Author[]\n     */\n    public $property;\n    \n    /**\n     * Union types: \n     *\n     * @var string|int\n     */\n    public $property;\n    \n    /**\n     * Nullable types: \n     *\n     * @var string|null\n     */\n    public $property;\n    \n    /**\n     * Mixed types: \n     *\n     * @var mixed|null\n     */\n    public $property;\n    \n    /**\n     * No type, which allows everything\n     */\n    public $property;\n}\n```\nWhen PHP 7.4 introduces typed properties, you'll be able to simply remove the doc blocks and type the properties with the new, built-in syntax.\n\n### Immutability\n\nIf you want your data object to be never changeable (this is a good idea in some cases), you can make it immutable:\n\n```php\nclass PostData extends DataTransferObject\n{\n    use MakeImmutable;\n    \n    /** @var string */\n    public $name;\n}\n```\n\n\nIf you only want to make a certain property immutable you can annotate this on the variable.\n\n```php\nclass PostData extends DataTransferObject\n{\n    /**\n     * @Immutable\n     * @var string $name\n     */\n    public $name;\n}\n```\n\nTrying to change a property of `$postData` after it's constructed, will result in a `ImmutableDtoException`.\n\n### Optional Properties\n\nBy default all dto properties are required. If you want to make certain properties on the dto optional:\n\n```php\nclass PostData extends DataTransferObject\n{\n    /**\n     * @Optional\n     * @var string $name\n     */\n    public $name;\n}\n```\n\n###### Note\nThe default value will NOT be set when a property is annotated as optional!\n\n### Additional Properties\n\nBy default only dto properties can be set on the dto. Attempting to input data that is not declared as a public property on the dto will throw a `UnknownPropertiesDtoException`.\nIf you want to allow additional properties you can do so by implementing the `AdditionalProperties` or `WithAdditionalProperties` interface.\n\nAdditionalProperties:\n\n```php\nclass PostData extends DataTransferObject implements AdditionalProperties\n{\n    /**\n     * @var string $name\n     */\n    public $name;\n}\n\n$dto = new PostData([\"name\" =\u003e \"foo\", \"address\" =\u003e \"bar\"]);\n$dto-\u003etoArray();\n\nreturns:\n[\"name\" =\u003e \"foo\"]\n```\n\nWithAdditionalProperties:\n\n```php\nclass PostData extends DataTransferObject implements WithAdditionalProperties\n{\n    /**\n     * @var string $name\n     */\n    public $name;\n}\n\n$dto = new PostData([\"name\" =\u003e \"foo\", \"address\" =\u003e \"bar\"]);\n$dto-\u003etoArray();\n\nreturns:\n[\"name\" =\u003e \"foo\", \"address\" =\u003e \"bar\"]\n```\n\n### Overriding \u0026 Adding Properties\n\nIf you want to add or override a certain value on the dto you can do it as follows:\n\nAdding Data:\n```php\n    public function create(PostData $data, User $user)\n    {\n        $data-\u003ewith('user_id', $user-\u003eid);\n        return $this-\u003erepository-\u003ecreate($data-\u003etoArray());\n    }\n```\n\nOverriding Property:\n\n```php\n    public function create(PostData $data, User $user)\n    {\n        if($this-\u003euser-\u003eisAdmin()){\n            $data-\u003eoverride('name', 'admin');\n        }\n        $data-\u003ewith('user_id', $user-\u003eid);\n        return $this-\u003erepository-\u003ecreate($data-\u003etoArray());\n    }\n```\n\n##### Notes:\n- You cannot add or override data on an immutable dto. You also can't override immutable properties.\n\n- You cannot use the with method to add properties that are declared as public properties on the dto.\n\n### Validation\n\n##### Constraints\nIf you want to validate the input of a property. You can do so through annotations.\n```php\nclass PostData extends DataTransferObject\n{\n    /**\n     * @var string\n     * @Assert\\NotBlank()\n     * @Assert\\Length(min = 3, max = 20)\n     */\n    public $name;\n}\n```\n##### Inheritence\nIf you want to extend a dto and add extra constraints or the optional annotation you can do so by adding the `Inherit` annotation.\nThis will merge all existing constraints from the parent class. If no type is specified on the current class it will also inherit the type of the parent dto.\n\n```php\nclass UpdatePostData extends PostData\n{\n    /**\n     * @Optional\n     * @Inherit\n     */\n    public $name;\n}\n```\n\n##### Notes:\n- If you are using phpstorm you can install this plugin: https://plugins.jetbrains.com/plugin/7320-php-annotations to typehint the annotations.\n- The `Optional` annotation will not be inherited from the parent class. This is to ensure you always have a clear overview of what values are required in a dto.\n- Validation is NOT done upon constructing the object. But only when accessing the variables. This can be done through the magic __get method `$dto-\u003eproperty` or when outputting the values of the array through the `toArray()` or `all()` methods. You could also call the `validate()` method manually. If the dto is not valid it will throw a `ValidatorException`. \n- The `ValidatorException` message will include all the property names and the constraints that have failed on that specific property. For example: `property 'author_name' is required`.\n- To implement this functionality the excellent `symfony\\validation` library was used. \nFor more info please check https://symfony.com/doc/current/validation.html .\n\n\n### Working with collections\n\nIf you're working with collections of DTOs, you probably want auto completion and proper type validation on your collections too.\nThis package adds a simple collection implementation, which you can extend from.\n\n```php\nuse \\Spatie\\DataTransferObject\\DataTransferObjectCollection;\n\nclass PostCollection extends DataTransferObjectCollection\n{\n    public function current(): PostData\n    {\n        return parent::current();\n    }\n}\n```\n\nBy overriding the `current` method, you'll get auto completion in your IDE, \nand use the collections like so.\n\n```php\nforeach ($postCollection as $postData) {\n    $postData-\u003e // … your IDE will provide autocompletion.\n}\n\n$postCollection[0]-\u003e // … and also here.\n```\n\nOf course you're free to implement your own static constructors:\n\n```php\nclass PostCollection extends DataTransferObjectCollection\n{\n    public static function create(array $data): PostCollection\n    {\n        $collection = [];\n\n        foreach ($data as $item)\n        {\n            $collection[] = PostData::create($item);\n        }\n\n        return new self($collection);\n    }\n}\n```\n\n### Automatic casting of nested DTOs\n\nIf you've got nested DTO fields, data passed to the parent DTO will automatically be casted.\n\n```php\nclass PostData extends DataTransferObject\n{\n    /** @var \\AuthorData */\n    public $author;\n}\n```\n\n`PostData` can now be constructed like so:\n\n```php\n$postData = new PostData([\n    'author' =\u003e [\n        'name' =\u003e 'Foo',\n    ],\n]);\n```\n\n### Automatic casting of nested array DTOs\n\nSimilarly to above, nested array DTOs will automatically be casted.\n\n```php\nclass TagData extends DataTransferObject\n{\n    /** @var string */\n   public $name;\n}\n\nclass PostData extends DataTransferObject\n{\n    /** @var \\TagData[] */\n   public $tags;\n}\n```\n\n`PostData` will automatically construct tags like such:\n\n```php\n$postData = new PostData([\n    'tags' =\u003e [\n        ['name' =\u003e 'foo'],\n        ['name' =\u003e 'bar']\n    ]\n]);\n```\n\n### Helper functions\n\nThere are also some helper functions provided for working with multiple properties at once. \n\n```php\n$postData-\u003eall();\n\n$postData\n    -\u003eonly('title', 'body')\n    -\u003etoArray();\n    \n$postData\n    -\u003eexcept('author')\n    -\u003etoArray();\n``` \n\nYou can also chain these methods:\n\n```php\n$postData\n    -\u003eexcept('title')\n    -\u003eexcept('body')\n    -\u003etoArray();\n```\n\nIt's important to note that `except` and `only` are immutable, they won't change the original data transfer object.\n\n### Exception handling\n\nBeside property type validation, you can also be certain that the data transfer object in its whole is always valid.\nOn outputting the data from a data transfer object (through the `all()` \u0026 `toArray()` methods and also when you access the properties of the dto e.g. `$dto-\u003ename`) , we'll validate whether all required properties are set, if the constraints are met and if each property is of the correct type. \nIf not, a `Larapie\\DataTransferObject\\Exceptions\\ValidatorException` will be thrown.\n\nLikewise, if you're trying to set non-defined properties, you'll get a `Larapie\\DataTransferObject\\Exceptions\\UnknownPropertiesDtoException`.\n\n### Testing\n\n``` bash\ncomposer test\n```\n\n### Changelog\n\nPlease see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.\n\n## Contributing\n\nPlease see [CONTRIBUTING](CONTRIBUTING.md) for details.\n\n## Credits\n\n- [Anthony Vancauwenberghe](https://github.com/larapie)\n- [Brent Roose](https://github.com/brendt)\n- [All Contributors](../../contributors)\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE.md) for more information.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flarapie%2Fdata-transfer-object","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flarapie%2Fdata-transfer-object","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flarapie%2Fdata-transfer-object/lists"}