PHP code example of taboritis / dto-wizard-php

1. Go to this page and download the library: Download taboritis/dto-wizard-php 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/ */

    

taboritis / dto-wizard-php example snippets


class User
{
    public string $name;
    public int $age;
    public int $score;
}

$rawData = ['name'=> 'John', 'age'=> 25];

$user = \Taboritis\DTO\Factory::create(User::class, $rawData);

$user->name     // John
$user->age      // 25
$user->score    // Error - property must be initialized

class User
{
    public readonly string $name;
}

$user = User::create(['name'=>'John']);
$user->name = 'Mary'; // Error: Cannot initialize readonly property 

class User
{
    private readonly string $name;
    
    public function getName(): string
    {
        return $this->name ?? 'default';
    }
}

$user = User::create(['name'=>'John'])
$user->name = 'Mary'; // Error: Cannot initialize readonly property 

class User
{
    public readonly int $age;
}

$user = User::create(['age' => '23']);  // '23' (string)
$user->age                              // 23 (integer)

class User
{
    public readonly bool $active;
}

$user = \Taboritis\DTO\Factory::create(User::class, ['active' => 0]);
$user->active // false (boolean)

class User
{
    public readonly bool $active;
}

$user = \Taboritis\DTO\Factory::create(User::class, ['name' => 11]);
$user->name // '11' (string)

class User
{
    public readonly int $age;
}

$user = \Taboritis\DTO\Factory::create(User::class, ['age' => '25.7']);
$user->age // 25 (int, but with warning about deprecation)

class User
{
    public readonly DateTimeImmutable $verifiedAt;
}

$user = \Taboritis\DTO\Factory::create(User::class, ['verifiedAt'=> '2020-10-10 00:00:00']);
$user->verifiedAt // instance of DateTimeImmutable

class Address
{
    public readonly string $street;
    public readonly string $number;
}

class User
{
    public readonly Address $address;
}

$user = \Taboritis\DTO\Factory::create(User::class, [
    'name' => 'Hudson (landlady)',
    'title' => 'Mrs.'
    'address' => [
        'street' => 'Baker Street',
        'number' => '221B'
    ]
]);

$user->address // instance of Department
$user->address->street // Baker Street