• This repository has been archived on 01/Nov/2022
  • Stars
    star
    2,220
  • Rank 20,780 (Top 0.5 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 6 years ago
  • Updated about 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Data transfer objects with batteries included

Warning We have decided to stop maintaining this package.

Consider migrating to spatie/laravel-data or cuyz/valinor.

Feel free to fork our code and adapt it to your needs.

Data transfer objects with batteries included

Latest Version on Packagist Test Total Downloads

Installation

You can install the package via composer:

composer require spatie/data-transfer-object
  • Note: v3 of this package only supports php:^8.0. If you're looking for the older version, check out v2.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Usage

The goal of this package is to make constructing objects from arrays of (serialized) data as easy as possible. Here's what a DTO looks like:

use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\DataTransferObject;

class MyDTO extends DataTransferObject
{
    public OtherDTO $otherDTO;
    
    public OtherDTOCollection $collection;
    
    #[CastWith(ComplexObjectCaster::class)]
    public ComplexObject $complexObject;
    
    public ComplexObjectWithCast $complexObjectWithCast;
    
    #[NumberBetween(1, 100)]
    public int $a;
    
    #[MapFrom('address.city')]
    public string $city;
}

You could construct this DTO like so:

$dto = new MyDTO(
    a: 5,
    collection: [
        ['id' => 1],
        ['id' => 2],
        ['id' => 3],
    ],
    complexObject: [
        'name' => 'test',
    ],
    complexObjectWithCast: [
        'name' => 'test',
    ],
    otherDTO: ['id' => 5],
);

Let's discuss all possibilities one by one.

Named arguments

Constructing a DTO can be done with named arguments. It's also possible to still use the old array notation. This example is equivalent to the one above.

$dto = new MyDTO([
    'a' => 5,
    'collection' => [
        ['id' => 1],
        ['id' => 2],
        ['id' => 3],
    ],
    'complexObject' => [
        'name' => 'test',
    ],
    'complexObjectWithCast' => [
        'name' => 'test',
    ],
    'otherDTO' => ['id' => 5],
]);

Value casts

If a DTO has a property that is another DTO or a DTO collection, the package will take care of automatically casting arrays of data to those DTOs:

$dto = new MyDTO(
    collection: [ // This will become an object of class OtherDTOCollection
        ['id' => 1],
        ['id' => 2], // Each item will be an instance of OtherDTO
        ['id' => 3],
    ],
    otherDTO: ['id' => 5], // This data will be cast to OtherDTO
);

Custom casters

You can build your own caster classes, which will take whatever input they are given, and will cast that input to the desired result.

Take a look at the ComplexObject:

class ComplexObject
{
    public string $name;
}

And its caster ComplexObjectCaster:

use Spatie\DataTransferObject\Caster;

class ComplexObjectCaster implements Caster
{
    /**
     * @param array|mixed $value
     *
     * @return mixed
     */
    public function cast(mixed $value): ComplexObject
    {
        return new ComplexObject(
            name: $value['name']
        );
    }
}

Class-specific casters

Instead of specifying which caster should be used for each property, you can also define that caster on the target class itself:

class MyDTO extends DataTransferObject
{
    public ComplexObjectWithCast $complexObjectWithCast;
}
#[CastWith(ComplexObjectWithCastCaster::class)]
class ComplexObjectWithCast
{
    public string $name;
}

Default casters

It's possible to define default casters on a DTO class itself. These casters will be used whenever a property with a given type is encountered within the DTO class.

#[
    DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class),
    DefaultCast(MyEnum::class, EnumCaster::class),
]
abstract class BaseDataTransferObject extends DataTransferObject
{
    public MyEnum $status; // EnumCaster will be used
    
    public DateTimeImmutable $date; // DateTimeImmutableCaster will be used
}

Using custom caster arguments

Any caster can be passed custom arguments, the built-in ArrayCaster implementation is a good example of how this may be used.

Using named arguments when passing input to your caster will help make your code more clear, but they are not required.

For example:

    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, itemType: Foo::class)]
    public array $collectionWithNamedArguments;
    
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, Foo::class)]
    public array $collectionWithoutNamedArguments;

Note that the first argument passed to the caster constructor is always the array with type(s) of the value being casted. All other arguments will be the ones passed as extra arguments in the CastWith attribute.

Validation

This package doesn't offer any specific validation functionality, but it does give you a way to build your own validation attributes. For example, NumberBetween is a user-implemented validation attribute:

class MyDTO extends DataTransferObject
{
    #[NumberBetween(1, 100)]
    public int $a;
}

It works like this under the hood:

#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
class NumberBetween implements Validator
{
    public function __construct(
        private int $min,
        private int $max
    ) {
    }

    public function validate(mixed $value): ValidationResult
    {
        if ($value < $this->min) {
            return ValidationResult::invalid("Value should be greater than or equal to {$this->min}");
        }

        if ($value > $this->max) {
            return ValidationResult::invalid("Value should be less than or equal to {$this->max}");
        }

        return ValidationResult::valid();
    }
}

Mapping

You can map a DTO property from a source property with a different name using the #[MapFrom] attribute.

It works with a "dot" notation property name or an index.

class PostDTO extends DataTransferObject
{
    #[MapFrom('postTitle')]
    public string $title;
    
    #[MapFrom('user.name')]
    public string $author;
}

$dto = new PostDTO([
    'postTitle' => 'Hello world',
    'user' => [
        'name' => 'John Doe'
    ]
]);
class UserDTO extends DataTransferObject
{

    #[MapFrom(0)]
    public string $firstName;
    
    #[MapFrom(1)]
    public string $lastName;
}

$dto = new UserDTO(['John', 'Doe']);

Sometimes you also want to map them during the transformation to Array. A typical usecase would be transformation from camel case to snake case. For that you can use the #[MapTo] attribute.

class UserDTO extends DataTransferObject
{

    #[MapFrom(0)]
    #[MapTo('first_name')]
    public string $firstName;
    
    #[MapFrom(1)]
    #[MapTo('last_name')]
    public string $lastName;
}

$dto = new UserDTO(['John', 'Doe']);
$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe'];
$dto->only('first_name')->toArray() // ['first_name' => 'John'];

Strict DTOs

The previous version of this package added the FlexibleDataTransferObject class which allowed you to ignore properties that didn't exist on the DTO. This behaviour has been changed, all DTOs are flexible now by default, but you can make them strict by using the #[Strict] attribute:

class NonStrictDto extends DataTransferObject
{
    public string $name;
}

// This works
new NonStrictDto(
    name: 'name',
    unknown: 'unknown'
);
use \Spatie\DataTransferObject\Attributes\Strict;

#[Strict]
class StrictDto extends DataTransferObject
{
    public string $name;
}

// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception
new StrictDto(
    name: 'name',
    unknown: 'unknown'
);

Helper functions

There are also some helper functions provided for working with multiple properties at once.

$postData->all();

$postData
    ->only('title', 'body')
    ->toArray();
    
$postData
    ->except('author')
    ->toArray();

Note that all() will simply return all properties, while toArray() will cast nested DTOs to arrays as well.

You can chain the except() and only() methods:

$postData
    ->except('title')
    ->except('body')
    ->toArray();

It's important to note that except() and only() are immutable, they won't change the original data transfer object.

Immutable DTOs and cloning

This package doesn't force immutable objects since PHP doesn't support them, but you're always encouraged to keep your DTOs immutable. To help you, there's a clone method on every DTO which accepts data to override:

$clone = $original->clone(other: ['name' => 'a']);

Note that no data in $original is changed.

Collections of DTOs

This version removes the DataTransferObjectCollection class. Instead you can use simple casters and your own collection classes.

Here's an example of casting a collection of DTOs to an array of DTOs:

class Bar extends DataTransferObject
{
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(FooArrayCaster::class)]
    public array $collectionOfFoo;
}

class Foo extends DataTransferObject
{
    public string $name;
}
class FooArrayCaster implements Caster
{
    public function cast(mixed $value): array
    {
        if (! is_array($value)) {
            throw new Exception("Can only cast arrays to Foo");
        }

        return array_map(
            fn (array $data) => new Foo(...$data),
            $value
        );
    }
}

If you don't want the redundant typehint, or want extended collection functionality; you could create your own collection classes using any collection implementation. In this example, we use Laravel's:

class Bar extends DataTransferObject
{
    #[CastWith(FooCollectionCaster::class)]
    public CollectionOfFoo $collectionOfFoo;
}

class Foo extends DataTransferObject
{
    public string $name;
}
use Illuminate\Support\Collection;

class CollectionOfFoo extends Collection
{
    // Add the correct return type here for static analyzers to know which type of array this is 
    public function offsetGet($key): Foo
    {
        return parent::offsetGet($key);
    }
}
class FooCollectionCaster implements Caster
{
    public function cast(mixed $value): CollectionOfFoo
    {
        return new CollectionOfFoo(array_map(
            fn (array $data) => new Foo(...$data),
            $value
        ));
    }
}

Simple arrays of DTOs

For a simple array of DTOs, or an object that implements PHP's built-in ArrayAccess, consider using the ArrayCaster which requires an item type to be provided:

class Bar extends DataTransferObject
{
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, itemType: Foo::class)]
    public array $collectionOfFoo;
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

External tools

  • json2dto: a GUI to convert JSON objects to DTO classes (with nesting support). Also provides a CLI tool for local usage.
  • Data Transfer Object Factory: Intelligently generates a DTO instance using the correct content for your properties based on its name and type.

Credits

Our Arr class contains functions copied from Laravels Arr helper.

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

laravel-permission

Associate users with roles and permissions
PHP
11,600
star
2

laravel-medialibrary

Associate files with Eloquent models
PHP
5,427
star
3

laravel-backup

A package to backup your Laravel app
PHP
5,337
star
4

laravel-activitylog

Log activity inside your Laravel app
PHP
5,316
star
5

browsershot

Convert HTML to an image, PDF or string
PHP
4,434
star
6

laravel-query-builder

Easily build Eloquent queries from API requests
PHP
3,675
star
7

laravel-analytics

A Laravel package to retrieve pageviews and other data from Google Analytics
PHP
2,948
star
8

image-optimizer

Easily optimize images using PHP
PHP
2,450
star
9

async

Easily run code asynchronously
PHP
2,401
star
10

crawler

An easy to use, powerful crawler implemented in PHP. Can execute Javascript.
PHP
2,400
star
11

laravel-responsecache

Speed up a Laravel app by caching the entire response
PHP
2,248
star
12

laravel-translatable

Making Eloquent models translatable
PHP
2,030
star
13

laravel-sitemap

Create and generate sitemaps with ease
PHP
2,011
star
14

dashboard.spatie.be

The source code of dashboard.spatie.be
PHP
1,940
star
15

laravel-fractal

An easy to use Fractal wrapper built for Laravel and Lumen applications
PHP
1,845
star
16

package-skeleton-laravel

A skeleton repository for Spatie's Laravel Packages
PHP
1,714
star
17

period

Complex period comparisons
PHP
1,618
star
18

laravel-collection-macros

A set of useful Laravel collection macros
PHP
1,602
star
19

laravel-newsletter

Manage Mailcoach and MailChimp newsletters in Laravel
PHP
1,570
star
20

checklist-going-live

The checklist that is used when a project is going live
1,489
star
21

laravel-tags

Add tags and taggable behaviour to your Laravel app
PHP
1,454
star
22

opening-hours

Query and format a set of opening hours
PHP
1,340
star
23

schema-org

A fluent builder Schema.org types and ld+json generator
PHP
1,337
star
24

eloquent-sortable

Sortable behaviour for Eloquent models
PHP
1,268
star
25

laravel-cookie-consent

Make your Laravel app comply with the crazy EU cookie law
PHP
1,268
star
26

laravel-data

Powerful data objects for Laravel
PHP
1,240
star
27

laravel-sluggable

An opinionated package to create slugs for Eloquent models
PHP
1,236
star
28

laravel-settings

Store strongly typed application settings
PHP
1,218
star
29

laravel-searchable

Pragmatically search through models and other sources
PHP
1,217
star
30

pdf-to-image

Convert a pdf to an image
PHP
1,207
star
31

laravel-mail-preview

A mail driver to quickly preview mail
PHP
1,171
star
32

once

A magic memoization function
PHP
1,159
star
33

laravel-honeypot

Preventing spam submitted through forms
PHP
1,134
star
34

laravel-image-optimizer

Optimize images in your Laravel app
PHP
1,121
star
35

laravel-google-calendar

Manage events on a Google Calendar
PHP
1,119
star
36

regex

A sane interface for php's built in preg_* functions
PHP
1,097
star
37

laravel-multitenancy

Make your Laravel app usable by multiple tenants
PHP
1,092
star
38

image

Manipulate images with an expressive API
PHP
1,064
star
39

array-to-xml

A simple class to convert an array to xml
PHP
1,056
star
40

laravel-uptime-monitor

A powerful and easy to configure uptime and ssl monitor
PHP
1,020
star
41

db-dumper

Dump the contents of a database
PHP
987
star
42

laravel-webhook-client

Receive webhooks in Laravel apps
PHP
985
star
43

laravel-model-states

State support for models
PHP
968
star
44

laravel-view-models

View models in Laravel
PHP
963
star
45

simple-excel

Read and write simple Excel and CSV files
PHP
930
star
46

laravel-web-tinker

Tinker in your browser
JavaScript
925
star
47

laravel-webhook-server

Send webhooks from Laravel apps
PHP
920
star
48

calendar-links

Generate add to calendar links for Google, iCal and other calendar systems
PHP
904
star
49

laravel-db-snapshots

Quickly dump and load databases
PHP
889
star
50

laravel-mix-purgecss

Zero-config Purgecss for Laravel Mix
JavaScript
887
star
51

laravel-schemaless-attributes

Add schemaless attributes to Eloquent models
PHP
880
star
52

blender

The Laravel template used for our CMS like projects
PHP
879
star
53

fork

A lightweight solution for running code concurrently in PHP
PHP
863
star
54

laravel-schedule-monitor

Monitor scheduled tasks in a Laravel app
PHP
859
star
55

laravel-menu

Html menu generator for Laravel
PHP
854
star
56

phpunit-watcher

A tool to automatically rerun PHPUnit tests when source code changes
PHP
831
star
57

laravel-failed-job-monitor

Get notified when a queued job fails
PHP
826
star
58

laravel-model-status

Easily add statuses to your models
PHP
818
star
59

form-backend-validation

An easy way to validate forms using back end logic
JavaScript
800
star
60

temporary-directory

A simple class to work with a temporary directory
PHP
796
star
61

laravel-feed

Easily generate RSS feeds
PHP
789
star
62

laravel-event-sourcing

The easiest way to get started with event sourcing in Laravel
PHP
772
star
63

enum

Strongly typed enums in PHP supporting autocompletion and refactoring
PHP
769
star
64

laravel-server-monitor

Don't let your servers just melt down
PHP
769
star
65

laravel-package-tools

Tools for creating Laravel packages
PHP
767
star
66

laravel-tail

An artisan command to tail your application logs
PHP
726
star
67

valuestore

Easily store some values
PHP
722
star
68

laravel-health

Check the health of your Laravel app
PHP
719
star
69

geocoder

Geocode addresses to coordinates
PHP
709
star
70

pdf-to-text

Extract text from a pdf
PHP
707
star
71

ssh

A lightweight package to execute commands over an SSH connection
PHP
696
star
72

menu

Html menu generator
PHP
688
star
73

laravel-url-signer

Create and validate signed URLs with a limited lifetime
PHP
685
star
74

ssl-certificate

A class to validate SSL certificates
PHP
675
star
75

laravel-route-attributes

Use PHP 8 attributes to register routes in a Laravel app
PHP
674
star
76

laravel-validation-rules

A set of useful Laravel validation rules
PHP
663
star
77

laravel-pdf

Create PDF files in Laravel apps
PHP
661
star
78

url

Parse, build and manipulate URL's
PHP
659
star
79

laravel-html

Painless html generation
PHP
654
star
80

laravel-event-projector

Event sourcing for Artisans πŸ“½
PHP
642
star
81

laravel-server-side-rendering

Server side rendering JavaScript in your Laravel application
PHP
636
star
82

vue-tabs-component

An easy way to display tabs with Vue
JavaScript
626
star
83

macroable

A trait to dynamically add methods to a class
PHP
621
star
84

laravel-blade-javascript

A Blade directive to export variables to JavaScript
PHP
618
star
85

laravel-onboard

A Laravel package to help track user onboarding steps
PHP
616
star
86

laravel-csp

Set content security policy headers in a Laravel app
PHP
614
star
87

laravel-cors

Send CORS headers in a Laravel application
PHP
607
star
88

laravel-short-schedule

Schedule artisan commands to run at a sub-minute frequency
PHP
607
star
89

laravel-translation-loader

Store your translations in the database or other sources
PHP
602
star
90

vue-table-component

A straight to the point Vue component to display tables
JavaScript
591
star
91

activitylog

A very simple activity logger to monitor the users of your website or application
PHP
586
star
92

phpunit-snapshot-assertions

A way to test without writing actual testΒ cases
PHP
584
star
93

http-status-check

CLI tool to crawl a website and check HTTP status codes
PHP
584
star
94

laravel-queueable-action

Queueable actions in Laravel
PHP
584
star
95

ray

Debug with Ray to fix problems faster
PHP
574
star
96

freek.dev

The sourcecode of freek.dev
PHP
571
star
97

server-side-rendering

Server side rendering JavaScript in a PHP application
PHP
568
star
98

string

String handling evolved
PHP
558
star
99

laravel-http-logger

Log HTTP requests in Laravel applications
PHP
538
star
100

laravel-blade-x

Use custom HTML components in your Blade views
PHP
533
star