PHP code example of fab2s / dt0

1. Go to this page and download the library: Download fab2s/dt0 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/ */

    

fab2s / dt0 example snippets


use fab2s\Dt0\Dt0;
use fab2s\Dt0\Attribute\Cast;
use fab2s\Dt0\Caster\DateTimeCaster;
use fab2s\Dt0\Caster\DateTimeFormatCaster;

class UserDto extends Dt0
{
    public readonly int $id;
    public readonly string $name;
    public readonly string $email;

    #[Cast(
        in: DateTimeCaster::class,
        out: new DateTimeFormatCaster('Y-m-d'),
    )]
    public readonly DateTimeImmutable $createdAt;

    #[Cast(default: 'user')]
    public readonly string $role;
}

// Create from anything
$user = UserDto::make(id: 1, name: 'Jane', email: '[email protected]', createdAt: '2024-01-15');
$user = UserDto::fromArray($apiResponse);
$user = UserDto::fromJson($jsonString);

// Access properties
$user->name;       // 'Jane'
$user->createdAt;  // DateTimeImmutable instance
$user->role;       // 'user' (default applied)

// Output with casting applied
$user->toArray();  // [..., 'createdAt' => DateTimeImmutable, ...]
$user->toJson();   // {..., "createdAt": "2024-01-15", ...}

// Immutable updates
$admin = $user->update(role: 'admin');
$user->role;   // 'user' (unchanged)
$admin->role;  // 'admin' (new instance)

use fab2s\Dt0\Attribute\Cast;
use fab2s\Dt0\Caster\DateTimeCaster;
use fab2s\Dt0\Caster\DateTimeFormatCaster;
use fab2s\Dt0\Caster\ScalarCaster;
use fab2s\Dt0\Caster\ScalarType;

class ArticleDto extends Dt0
{
    public readonly string $title;

    #[Cast(in: new ScalarCaster(ScalarType::int))]
    public readonly int $viewCount;

    #[Cast(
        in: DateTimeCaster::class,
        out: new DateTimeFormatCaster(DateTimeFormatCaster::ISO),
    )]
    public readonly DateTimeImmutable $publishedAt;
}

$article = ArticleDto::make(
    title: 'Hello World',
    viewCount: '42',           // string -> int
    publishedAt: '2024-01-15', // string -> DateTimeImmutable
);

#[Casts(
    status: new Cast(default: 'pending'),
    priority: new Cast(default: 0),
    createdAt: new Cast(in: DateTimeCaster::class),
)]
class TaskDto extends Dt0
{
    public readonly string $title;
    public readonly string $status;
    public readonly int $priority;
    public readonly DateTime $createdAt;
}

class OrderDto extends Dt0
{
    public readonly Status $status;      // BackedEnum — auto-cast from string/int
    public readonly AddressDto $address; // Nested Dt0 — auto-cast from array/JSON
}

use fab2s\Dt0\Dt0;
use fab2s\Dt0\Attribute\Rule;
use fab2s\Dt0\Attribute\Rules;
use fab2s\Dt0\Attribute\Validate;
use fab2s\Dt0\Validator\Validator;

#[Validate(Validator::class)]
#[Rules(
    email: new Rule(' ?string $message;
}

// Throws ValidationException on failure
$contact = ContactDto::withValidation(
    email: '[email protected]',
    name: 'John',
    message: 'Hello!',
);

$dto->toArray();      // Array with objects intact, output casters applied
$dto->toJsonArray();  // Array with objects serialized (JsonSerializable)
$dto->toJson();       // JSON string
$dto->toGz();         // Gzipped JSON string
json_encode($dto);    // JSON (implements JsonSerializable)
(string) $dto;        // JSON (implements Stringable)

// Exclude sensitive fields
$dto->without('password', 'apiKey')->toJson();

// Include only specific fields
$dto->only('id', 'name')->toArray();

// Add computed or protected properties
$dto->with('fullName', fn($d) => "$d->firstName $d->lastName")->toArray();
$dto->with('total', true)->toArray();       // calls getTotal()
$dto->with('internalField')->toArray();     // exposes protected property

$copy = $dto->clone();
$updated = $dto->update(name: 'Jane', role: 'admin');
$dto->equals($updated);  // false

// Serialization round-trip
$restored = unserialize(serialize($dto));
$dto->equals($restored);  // true

class ApiResponseDto extends Dt0
{
    #[Cast(renameFrom: 'created_at', renameTo: 'createdAtStr')]
    public readonly string $createdAt;

    // Accept multiple input names
    #[Cast(renameFrom: ['user_name', 'username', 'login'])]
    public readonly string $userName;
}

class ConfigDto extends Dt0
{
    #[Cast(default: 3600)]
    public readonly int $ttl;

    #[Cast(default: null)]
    public readonly ?string $prefix;

    #[Cast(default: true)]
    public readonly bool $enabled;
}

$config = ConfigDto::make();  // All defaults applied

class TimestampedDto extends Dt0
{
    #[Cast(in: DateTimeCaster::class, out: new DateTimeFormatCaster(DateTimeFormatCaster::ISO))]
    public readonly DateTimeImmutable $createdAt;
}

// Inherits Cast from TimestampedDto
class ArticleDto extends TimestampedDto
{
    public readonly string $title;
    public readonly DateTimeImmutable $createdAt;  // Redeclare for PHP < 8.4
}

$article = ArticleDto::make(title: 'Hello', createdAt: '2024-01-15');
$article->createdAt;  // DateTimeImmutable (inherited cast applied)
shell
php benchmark/compare-spatie.php