PHP code example of uvarats / dto

1. Go to this page and download the library: Download uvarats/dto library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

uvarats / dto example snippets


final class LoginDto extends Data 
{
    public function __construct(
        public readonly ?string $username = null,
        public readonly ?string $password = null,
    ) 
    {
    }
}

$data = [
    'username' => 'some_user',
    'password' => '123456'
];

$dto = LoginDto::from($data);

// Collection 

$data = [
    [
        'username' => 'some_user',
        'password' => '123456'
    ],
    [
        'username' => 'some_user',
        'password' => '123456'
    ],
];

$dtos = LoginDto::collection($data);

enum State: string 
{
    case NEW = 'new';
    case UNDER_MODERATION = 'under_moderation';
    case PUBLISHED = 'published';
}

final class AuthorDto extends Data 
{
    public function __construct(
        public readonly string $userId,
        public readonly string $username,
    ) 
    {
    }
}

final class ExampleDto extends Data
{
    public function __construct(
        public readonly string $name,
        public readonly State $state,
        public readonly AuthorDto $author
    ) 
    {
    }
}

$data = [
    'name' => 'Some name',
    'state' => 'new',
    'author' => [
        'userId' => '232',
        'username' => 'user',    
    ]
];

final class TestDto extends Data
{
    public function __construct(
        public $name,                           // Exception
        public string|array $id,                // Exception
        public callable&iterable $caliterable   // Also exception
    ) 
    {
    }
}