PHPackages                             rmezhuev/data-transfer-object - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rmezhuev/data-transfer-object

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rmezhuev/data-transfer-object
=============================

Plain and simple immutable DTO pattern implementation based on php annotations

v1.3.0(1y ago)212.5k↓19%MITPHPPHP ^8.0CI failing

Since Mar 29Pushed 1y ago2 watchersCompare

[ Source](https://github.com/rmezhuev/data-transfer-object)[ Packagist](https://packagist.org/packages/rmezhuev/data-transfer-object)[ RSS](/packages/rmezhuev-data-transfer-object/feed)WikiDiscussions master Synced 3d ago

READMEChangelogDependencies (6)Versions (12)Used By (0)

Flexible Data transfer objects
==============================

[](#flexible-data-transfer-objects)

Implementation of immutable Data Transfer Object (DTO) concept for safe transferring data between architecture layers of application. Like transferring data received from API to the application core. Arrays don't provide reliable mechanism for that purpose, due to the lack of strict structure, validation, type checks and immutability. Data Transfer Object (DTO) can solve this problem remaining a simple data structure object without business logic, while at the same time providing powerful tools for validating, structuring and serializing data.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require rmezhuev/data-transfer-object
```

Usage
-----

[](#usage)

### Declaration

[](#declaration)

The package contains `RMezhuev\DTO\DataObject` class, to create your own DTO just extend it from this class.

```
use RMezhuev\DTO\DataObject;

/**
 * @property string $name
 * @property string $email
 * @property string|int|null $age
 * @property array|null $phone
 * @property CustomType|null $details
 */
class PersonDto extends DataObject
{

}
```

To make the class `IDE friendly` and immutable, supported properties are declared using `phpdoc`. All properties and values are validated on object construction. For optional properties, type `null` must be added to the description of their types.

### Initialization

[](#initialization)

#### Constructor

[](#constructor)

Constructor of the object expects an associative array of properties with names matching the `phpdoc` names and with values of the supported types.

```
$personDto = new PersonDto([
    'email' =>'john.doe@gmail.com',
    'name' => 'John Doe',
    'age' => 35,
]);
```

#### Factory methods

[](#factory-methods)

Most likely, you will need to initialize your DTO from different data structures depending on the context of use. To do this, you can use separate factory methods for each specific case.

```
class PersonDto extends DataObject
{
    public static function fromRequest(Request $request): self
    {
        return new self(
            $request->only([
                'email',
                'name',
            ])
        );
    }

    public static function fromApi(array $data): self
    {
        return new self([
              'email' => $data['primary_email'],
              'name' => $data['full_name'],
        ]);

    }
}
```

### Accessing data

[](#accessing-data)

#### By magic getter or array notation

[](#by-magic-getter-or-array-notation)

All properties are accessible through magic getter defined in base class. You can also use array brackets notation because the class also implements `Arrayable` interface as well.

```
$personDto = new PersonDto([
    'name' => 'John Doe',
    'email' =>'john.doe@gmail.com',
]);

echo($personDto->name); //John Doe
echo($personDto->email); //john.doe@gmail.com

echo($personDto['name']); //John Doe
echo($personDto['email']); //john.doe@gmail.com
```

### Serialization

[](#serialization)

DTO supports `toArray()` and `toJson()` serialization out of the box and implements `Illuminate\Contracts\Support\Arrayable` and `Illuminate\Contracts\Support\Jsonable` corresponding interfaces for better integration with `Laravel` framework.

#### Snake case

[](#snake-case)

By default during serialization all names will be converted to the snake case so `fullName` will become `full_name`. To disable this behavior you can set `$snakeOnSerialize = false`

```
class PersonDto extends DataObject
{
	protected $snakeOnSerialize = false;
}
```

#### Partial mode

[](#partial-mode)

On serialization DTO allows you to specify `partial` mode. In this case only implicitly initialized fields will be serialized, all the rest will be excluded. This mode is useful for partial updates, when you need to discern if `nullable` field was implicitly set to `null` value or wasn't set at all.

```
$personDto = new PersonDto([
    'name' => 'John Doe',
    'email' =>'john.doe@gmail.com',
]);

$personDto->toArray();
//      Result:
//        [
//            "name" => "John Doe"
//            "email" => "john.doe@gmail.com"
//            "age" => null
//            "phone" => null
//            "details" => null
//        ]

$personDto->partial()->toArray();
//      Result:
//        [
//            "name" => "John Doe"
//            "email" => "john.doe@gmail.com"
//        ]
```

#### Custom serialization

[](#custom-serialization)

Serialization methods can be easily overwritten in child class when built-in methods do not meet your needs or if you want to make it more explicit.

```
class PersonDto extends DataObject
{
    public static function toArray(): array
    {
        return [
            'full_name' => $this->name,
            'email' => $this->email,
            'year' => date("Y") - $this->age
        ];
    }
}
```

Exception handling
------------------

[](#exception-handling)

In addition to property type validation, on constructing data transfer object will check if all required properties are set. If not, then `RMezhuev\DTO\Exceptions\DataObjectException` will be thrown. Likewise, if you're trying to set unsupported or change existing properties, you'll get the same exception.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

License
-------

[](#license)

The MIT License (MIT). Please see [License](https://opensource.org/licenses/MIT) for more information.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance42

Moderate activity, may be stable

Popularity27

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity68

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~181 days

Recently: every ~206 days

Total

11

Last Release

471d ago

PHP version history (4 changes)v1.0.0PHP ^7.1

v1.0.3PHP ^7.1|^8.0

v1.0.4PHP ^7.4|^8.0

v1.1.0PHP ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/7c36171aa51f30de52ff924856eab0656fbea1cb7d3cc2d032e85ec07f21514b?d=identicon)[rmezhuev](/maintainers/rmezhuev)

---

Top Contributors

[![rmezhuev](https://avatars.githubusercontent.com/u/279093?v=4)](https://github.com/rmezhuev "rmezhuev (2 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rmezhuev-data-transfer-object/health.svg)

```
[![Health](https://phpackages.com/badges/rmezhuev-data-transfer-object/health.svg)](https://phpackages.com/packages/rmezhuev-data-transfer-object)
```

###  Alternatives

[craftcms/cms

Craft CMS

3.6k3.6M3.1k](/packages/craftcms-cms)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[web-auth/webauthn-lib

FIDO2/Webauthn Support For PHP

12310.5M135](/packages/web-auth-webauthn-lib)[symfony/ai-platform

PHP library for interacting with AI platform provider.

521.4M291](/packages/symfony-ai-platform)[web-auth/webauthn-framework

FIDO2/Webauthn library for PHP and Symfony Bundle.

515100.5k3](/packages/web-auth-webauthn-framework)[2lenet/crudit-bundle

The easy like Crud'it Bundle.

1616.4k14](/packages/2lenet-crudit-bundle)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
