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!',
);