PHPackages                             horizom/dto - 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. horizom/dto

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

horizom/dto
===========

Data Transfer Objects for all PHP applications

5.1.0(2y ago)21.5kMITPHPPHP ^7.0||^8.0

Since Nov 18Pushed 2y ago1 watchersCompare

[ Source](https://github.com/horizom/dto)[ Packagist](https://packagist.org/packages/horizom/dto)[ RSS](/packages/horizom-dto/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (9)DependenciesVersions (10)Used By (0)

Horizom DTO
===========

[](#horizom-dto)

Data Transfer Objects for all PHP applications.

[![Total Downloads](https://camo.githubusercontent.com/0f48e36bb7f8c4c5023aa129494bcedc1616d299aedaa158619db5171573ef44/68747470733a2f2f706f7365722e707567782e6f72672f686f72697a6f6d2f64746f2f642f746f74616c2e737667)](https://packagist.org/packages/horizom/dto)[![Latest Stable Version](https://camo.githubusercontent.com/8df0760b9eb90a0b747405e0b2c02d97b593fea39355df2aeabbd0a667b53115/68747470733a2f2f706f7365722e707567782e6f72672f686f72697a6f6d2f64746f2f762f737461626c652e737667)](https://packagist.org/packages/horizom/dto)[![License](https://camo.githubusercontent.com/e55cd25fd5dcc662e9c31380f7a5346222a80184a8134895f559dde6a2e3be69/68747470733a2f2f706f7365722e707567782e6f72672f686f72697a6f6d2f64746f2f6c6963656e73652e737667)](https://packagist.org/packages/horizom/dto)

Data Transfer Objects (DTOs) are objects that are used to transfer data between systems. DTOs are typically used in applications to provide a simple, consistent format for transferring data between different parts of the application, such as between the user interface and the business logic.

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

[](#installation)

```
composer require horizom/dto
```

Usage
-----

[](#usage)

### Defining DTO Properties

[](#defining-dto-properties)

```
use Horizom\DTO\DTO;

class UserDTO extends DTO
{
    public string $name;

    public string $email;

    public string $password;
}
```

### Creating DTO Instances

[](#creating-dto-instances)

You can create a `DTO` instance on many ways:

#### From array

[](#from-array)

```
$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B'
]);
```

You can also use the `fromArray` static method:

```
$dto = UserDTO::fromArray([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B'
]);
```

#### From JSON strings

[](#from-json-strings)

```
$dto = UserDTO::fromJson('{"name": "John Doe", "email": "john.doe@example.com", "password": "s3CreT!@1a2B"}');
```

### Accessing DTO Data

[](#accessing-dto-data)

After you create your `DTO` instance, you can access any properties like an `object`:

```
$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B'
]);

$dto->name; // 'John Doe'
$dto->email; // 'john.doe@example.com'
$dto->password; // 's3CreT!@1a2B'
```

### Casting DTO Properties

[](#casting-dto-properties)

You can cast your `DTO` properties to some types:

```
use App\Enums\UserRole;
use Carbon\Carbon;
use Horizom\DTO\DTO;
use DateTimeImmutable;
use Horizom\DTO\Casting\ArrayCast;
use Horizom\DTO\Casting\EnumCast;

class UserDTO extends DTO
{
    public string $id;

    public string $name;

    public string $email;

    public string $password;

    public Carbon $created_at;

    public DateTimeImmutable $updated_at;

    public array $roles;

    protected function casts()
    {
        return [
            'id' => 'integer',
            'name' => 'string',
            'email' => 'string',
            'password' => 'string',
            'created_at' => Carbon::class,
            'updated_at' => DateTimeImmutable::class,
            'admin_role' => UserRole::class,
            'roles' => new ArrayCast(new EnumCast(UserRole::class)),
        ];
    }
}
```

### Defining Default Values

[](#defining-default-values)

Sometimes we can have properties that are optional and that can have default values. You can define the default values for your `DTO` properties in the `defaults` function:

```
use Horizom\DTO\DTO;
use Illuminate\Support\Str;

class UserDTO extends DTO
{
    // ...

    protected function defaults()
    {
        return [
            'username' => Str::slug($this->name),
        ];
    }
}
```

With the `DTO` definition above you could run:

```
$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B'
]);

$dto->username; // 'john_doe'
```

### Transforming DTO Data

[](#transforming-dto-data)

You can convert your DTO to some formats:

#### To array

[](#to-array)

```
$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B',
]);

$dto->toArray();
// [
//     "name" => "John Doe",
//     "email" => "john.doe@example.com",
//     "password" => "s3CreT!@1a2B",
// ]
```

#### To JSON string

[](#to-json-string)

```
$dto = new UserDTO([
    'name' => 'John Doe',
    'email' => 'john.doe@example.com',
    'password' => 's3CreT!@1a2B',
]);

$dto->toJson();
// '{"name":"John Doe","email":"john.doe@example.com","password":"s3CreT!@1a2B"}'
```

### Create Your Own Type Cast

[](#create-your-own-type-cast)

#### Castable classes

[](#castable-classes)

You can easily create new `Castable` types for your project by implementing the `Horizom\DTO\Contracts\CastableContract` interface. This interface has a single method that must be implemented:

```
public function cast(string $property, mixed $value): mixed;
```

Let's say that you have a `URLWrapper` class in your project, and you want that when passing a URL into your `DTO` it will always return a `URLWrapper` instance instead of a simple string:

```
use Horizom\DTO\Contracts\CastableContract;

class URLCast implements CastableContract
{
    public function cast(string $property, mixed $value): URLWrapper
    {
        return new URLWrapper($value);
    }
}
```

Then you could apply this to your DTO:

```
use Horizom\DTO\DTO;

class CustomDTO extends DTO
{
    protected function casts()
    {
        return [
            'url' => new URLCast(),
        ];
    }

    protected function defaults()
    {
        return [];
    }
}
```

#### Callable casts

[](#callable-casts)

You can also create new Castable types for your project by using a callable/callback:

```
use Horizom\DTO\DTO;

class CustomDTO extends DTO
{
    protected function casts(): array
    {
        return [
            'url' => function (string $property, mixed $value) {
                return new URLWrapper($value);
            },
        ];
    }

    protected function defaults(): array
    {
        return [];
    }
}
```

Or you can use a static method:

```
use Horizom\DTO\Casting\Cast;
use Horizom\DTO\DTO;

class CustomDTO extends DTO
{
    protected function casts()
    {
        return [
            'url' => Cast::make(
                function (string $property, mixed $value) {
                    return new URLWrapper($value);
                },
                function (string $property, URLWrapper $value) {
                    return $value->toString();
                }
            )
        ];
    }

    protected function defaults()
    {
        return [];
    }
}
```

### Case of possibility of extending with Laravel

[](#case-of-possibility-of-extending-with-laravel)

You can extend the `DTO` class to create your own `DTO` class with some custom methods:

```
use App\Http\Resources\UserResource;
use Horizom\DTO\DTO;
use Illuminate\Database\Eloquent\Model;

class UserDTO extends DTO
{
    public int $id;

    public string $name;

    public string $email;

    public string $password;

    public Carbon $created_at;

    public CarbonImmutable $updated_at;

    public DateTimeImmutable $verified_at;

    public static function fromModel(Model $model) {
        return new self($model->toArray());
    }

    public function toModel() {
        return new Model($this->toArray());
    }

    public function toResource() {
        return new UserResource($this->toArray());
    }

    protected function casts()
    {
        return [
            'id' => 'integer',
            'name' => 'string',
            'email' => 'string',
            'password' => 'string',
            'created_at' => Carbon::class,
            'updated_at' => CarbonImmutable::class,
            'verified_at' => DateTimeImmutable::class,
        ];
    }
}
```

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity22

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity53

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

Recently: every ~24 days

Total

9

Last Release

800d ago

Major Versions

1.4.0 → 5.0.02024-03-09

PHP version history (2 changes)1.0.0PHP &gt;=7.0

5.0.0PHP ^7.0||^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/412f8e786e65f078584b4bc2c0b7a44af095ab2c0d19a5fb7985598576ca4fda?d=identicon)[lambirou](/maintainers/lambirou)

---

Top Contributors

[![lambirou](https://avatars.githubusercontent.com/u/1428556?v=4)](https://github.com/lambirou "lambirou (12 commits)")

---

Tags

datadtoobjecttransferdata-transfer-objectdto

### Embed Badge

![Health badge](/badges/horizom-dto/health.svg)

```
[![Health](https://phpackages.com/badges/horizom-dto/health.svg)](https://phpackages.com/packages/horizom-dto)
```

###  Alternatives

[cerbero/dto

Data Transfer Object (DTO)

17119.4k1](/packages/cerbero-dto)

PHPackages © 2026

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