Transform Data into Type-safe DTOs with this PHP Package

This PHP Data Model package provides a lightweight, non-invasive way to hydrate type-safe PHP objects recursively. It uses reflection and PHP attributes to hydrate objects and instantiate them based on type hints:

class Address
{
    use \Zerotoprod\DataModel\DataModel;

    public string $street;
    public string $city;
}

class User
{
    use \Zerotoprod\DataModel\DataModel;

    public string $username;
    public Address $address;
}

$User = User::from([
    'username' => 'John Doe',
    'address' => [
        'street' => '123 Main St',
        'city' => 'Hometown',
    ],
]);

echo $User->address->city; // Hometown

Main Features

This package also includes advanced features like required properties that are enforced via a PHP attribute:

use Zerotoprod\DataModel\Describe;

class User
{
    use \Zerotoprod\DataModel\DataModel;

    #[Describe(['required' => true])]
    public string $username;

    public string $email;
}

User::from(['email' => 'john@example.com']);
// Throws PropertyRequiredException exception:
// Property: username is required

Additional related packages also provide helpers, factories, transformers, and more. You can get started with this package by reading the documentation; the source code is also available on GitHub at zero-to-prod/data-model.


The post Transform Data into Type-safe DTOs with this PHP Package appeared first on Laravel News.

Join the Laravel Newsletter to get all the latest Laravel articles like this directly in your inbox.