arnapou/dto

Library - Simple library to create objects from arrays and vice-versa.

v4.0 2024-04-02 23:48 UTC

This package is auto-updated.

Last update: 2024-04-18 20:08:51 UTC


README

pipeline coverage

This library is a simple tool to create objects from arrays and vice-versa.

Installation

composer require arnapou/dto

packagist 👉️ arnapou/dto

Example

We want to create an immutable DTO from an array (got from JSON for instance).

use Arnapou\Dto\Converter\Result\Success;
use Arnapou\Dto\Converter\Result\Unsupported;

readonly class ImmutableUser
{
    public function __construct(
        public int $id,
        public string $name,
        public DateTimeImmutable $createdAt = new DateTimeImmutable(),
    ) {
    }
}

$converter = new \Arnapou\Dto\DtoConverter();
$result = $converter->fromData(
    [
        'id' => '1',
        'name' => 'Arnaud',
    ], 
    ImmutableUser::class
); 
$user = $result->get();

var_dump($user->name);
// string(6) "Arnaud"

The production of an array from the object is also possible

$array = $converter->toData($user);

That's all, folks !

Why using it

No need to extend classes or implement interface for your DTOs : 100% decoupled and easy to manage.

If you need to manage lists, well, yes, you need to carry the list into an object.

You may want to reuse the Collection interface of this project, but I recommend to keep your domain logic safe with its own classes, and then implement your own interfaces.

Look at the example custom_list for a basic custom implementation of a list.

Obviously, for nested objects, you will need recurse the converter like in the CollectionConverter of this library.

Customization

Need to retrieve the schema elsewhere than Reflection ? Implement your own Schema.

Need to manage your own classes ? Implement your own TypedDataConverter or DataConverter.

The code is fairly simple and small : ~1000 LoC only.

Changelog versions

StartTag, BranchPhp
02/04/20244.x, main8.3
25/11/20233.x8.3
17/09/20232.x8.2
03/09/20231.x8.2