PHPackages                             jamielsharief/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. jamielsharief/data-transfer-object

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

jamielsharief/data-transfer-object
==================================

Data Transfer Object (DTO)

0.1.2(5y ago)24221MITPHPPHP &gt;=7.4.0

Since Nov 30Pushed 5y ago1 watchersCompare

[ Source](https://github.com/jamielsharief/data-transfer-object)[ Packagist](https://packagist.org/packages/jamielsharief/data-transfer-object)[ RSS](/packages/jamielsharief-data-transfer-object/feed)WikiDiscussions main Synced today

READMEChangelogDependencies (2)Versions (4)Used By (1)

Data Transfer Object (DTO)
==========================

[](#data-transfer-object-dto)

[![license](https://camo.githubusercontent.com/6fdb99389fe9d9e8a5c197002a191ace7c8b12a2020c0fa5756cf17aa08a4966/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874477265656e2e737667)](https://camo.githubusercontent.com/6fdb99389fe9d9e8a5c197002a191ace7c8b12a2020c0fa5756cf17aa08a4966/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874477265656e2e737667)[![build](https://github.com/jamielsharief/data-transfer-object/workflows/CI/badge.svg)](https://github.com/jamielsharief/data-transfer-object/actions)[![coverage status](https://camo.githubusercontent.com/aad576656a3e2f20cd2e28305bec840b22f076234800d88c8e93821da994a364/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6a616d69656c736861726965662f646174612d7472616e736665722d6f626a6563742f62616467652e7376673f6272616e63683d6d61696e)](https://coveralls.io/github/jamielsharief/data-transfer-object?branch=main)

Create
------

[](#create)

To create a `DataTransferObject` create the class and use public properties.

```
use DataTransferObject\DataTransferObject;

class Employee extends DataTransferObject
{
    public string $name;
    public string $email;
    public ?Employee $reportsTo;
    public int $age;
    public bool $active = true;

    /**
     * @var \App\DataTransferObject\Employee[] $subordinates
     */
    public array $subordinates = [];
}
```

Then to set the data

```
$employee = new Employee();
$employee->name = 'sarah';
```

You can also mass set the properties using an array when constructing the argument. Note this only sets, does not convert or extract, see `fromArray`

```
 $sarah = new Employee([
            'name' => 'Sarah',
            'email' => 'sarah@example.com',
            'reportsTo' => $claire
        ]);
```

### Build

[](#build)

When you use the `DataTransferObject` constructor, it simply sets the values that you are providing, however when you need to convert data and cast types, you can use the `fromArray` method.

The `fromArray` extracts relevant data and it:

1. casts built in types bool, int, string, float etc
2. will create a `DataTransferObject`, `DateTime` or any other object that has a `__set_state` magic method.

It will only extract fields defined in the `DataTransferObject` and will only throw an error, if after extracting data, a property on the `DataTransferObject` was not initialized.

For example, related `DataTransferObjects` such as `belongsTo` and `hasMany` will be marshalled. For `hasMany` to work create an array and set the DocBlock definition like below:

```
class Employee extends DataTransferObject
{
    public string $name;
    public string $email;
    public ?Employee $reportsTo;

    /**
     * @var \App\DataTransferObjects\Employee[] $subordinates
     */
    public array $subordinates = [];
}
```

To use the `fromArray` method

```
 $employee = Employee::fromArray([
    'name' => 'Sarah',
    'email' => 'sarah@example.com',
    'reportsTo' => [
        'name' => 'Claire',
        'email' => 'claire@example.com',
    ],
    'subordinates' => [
        [
            'name' => 'Jon',
            'email' => 'jon@example.com'
        ]
    ]
]);
```

### Converting to an Array

[](#converting-to-an-array)

To convert the `DataTransferObject` and any **nested** objects to an array if the object has an `toArray` method or does not have a `__toString` method.

```
$employee->toArray();
```

### Serialization / Deserialization

[](#serialization--deserialization)

The default serialization method is JSON, for a different method, e.g. XML you can override the `serialize` and `deserialize` methods. Only public properties will be used in the serialization and therefore deserialization process.

### To string

[](#to-string)

To convert a `DataTransferObject` to a string.

```
$employee->toString();
```

### From string

[](#from-string)

To convert a string to a `DataTransferObject`

```
$employee = Contact::fromString(
    '{"name":"Jon","company":"Snow Enterprises","email":"jon@example.com","age":33,"unsubscribed":false}'
);
```

### Initialize Hook

[](#initialize-hook)

When the `DataTransferObject` is constructed it will call `initialize` method if it is available, this is a hook incase you need to override the constructor.

### Exception Handling

[](#exception-handling)

If you try to set or get a property that does not exist, a `RuntimeException` will be thrown.

Resources
---------

[](#resources)

- [Data Transfer Object (DTO) - Martin Fowler](https://martinfowler.com/eaaCatalog/dataTransferObject.html)
- [Data Transfer Object - Wikipedia](https://en.wikipedia.org/wiki/Data_transfer_object)

###  Health Score

25

—

LowBetter than 35% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity46

Maturing project, gaining track record

 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 ~33 days

Total

3

Last Release

1974d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7718a059aa8ef3d6e9f6e5bd7f4d5b09b7321a059f2669e61546d1a665fbb372?d=identicon)[jamielsharief](/maintainers/jamielsharief)

---

Top Contributors

[![jamielsharief](https://avatars.githubusercontent.com/u/20553479?v=4)](https://github.com/jamielsharief "jamielsharief (7 commits)")

---

Tags

data-transfer-objectdtodata-transfer-objectdto

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[cerbero/dto

Data Transfer Object (DTO)

19121.6k1](/packages/cerbero-dto)[php-collective/dto

Framework-agnostic Data Transfer Object library with code generation

2814.6k7](/packages/php-collective-dto)

PHPackages © 2026

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