Skip to content

A Data objects library simplifies data transfer, ensuring structure, validation, and separation of concerns.

License

Notifications You must be signed in to change notification settings

nuxtifyts/php-dto

Folders and files

NameName
Last commit message
Last commit date

Latest commit

7aaf035 · Feb 4, 2025
Feb 1, 2025
Feb 4, 2025
Feb 1, 2025
Feb 1, 2025
Jan 27, 2025
Dec 26, 2024
Feb 1, 2025
Dec 28, 2024
Jan 27, 2025
Jan 1, 2025
Dec 7, 2024
Dec 28, 2024

Repository files navigation

PHP Pure Data objects

GitHub License Packagist Version PhpStan Level PHPStan Checks CI Tests Test Coverage

This package enabled the creation of data objects which can be used in various ways. Using modern PHP syntax, it allows you to hydrate data from arrays, objects, and other data sources. As well as carrying out the data, type validation and serialize the data for any purpose.

To create a data class, you will need to declare a readonly class that extends Data class. Then you can define the properties of the class and their types.

use Nuxtifyts\PhpDto\Data;
use Nuxtifyts\PhpDto\Attributes\Property\Aliases;
use Nuxtifyts\PhpDto\Attributes\Property\Computed;

final readonly class UserData extends Data
{
    #[Computed]
    public string $fullName;

    public function __construct(
        public string $firstName,
        #[Aliases('familyName')]
        public string $lastName
    ) {
        $this->fullName = "$this->firstName $this->lastName";
    }
}

You can then create an instance of the class from a mixed value. The DTO will then attempt to hydrate the object with the given data.

$data = [
    'firstName' => 'John',
    'lastName' => 'Doe',
];

$user = UserData::from($data);

DTOs can also be serialized to an array:

$user = new UserData('John', 'Doe');

$userData = $user->toArray();

// Or transform to a JSON string

$userData = $user->toJson();

Check out the Quick start guide for more information.

Note

This package was inspired from the spatie/data-transfer-object package. The main thing that I tried to focus on when creating this package is to make it outside of Laravel ecosystem, meaning: no dependency on illuminate/support.

Requirements

  • PHP 8.4 or higher
  • That's it!

Installation

You can install the package via composer:

composer require nuxtifyts/php-dto