PHP code example of gpalyan / dto-forge

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

    

gpalyan / dto-forge example snippets


use Forge\Dto\Support\BaseDto;

final class SimpleDto extends BaseDto
{
    public ?string $name = null;
    public ?string $age = null;
    public ?string $address = null;
}

// From array
$dto = new SimpleDto([
    'name' => 'John Doe',
    'age' => '25',
    'address' => 'Some address'
]);

// From JSON
$dto = new SimpleDto(json_encode($data));

// Using setters
$dto = new SimpleDto()
    ->setName('John Doe')
    ->setAge('25')
    ->setAddress('Some address');

// Access via properties or getters
echo $dto->name;           // John Doe
echo $dto->getName();      // John Doe

if ($dto->hasName()) {
    echo "Name is set";
}


$dto = new SimpleDto();
$dto->fill([
    'name' => 'John Doe',
    'age' => '25'
]);

// Overwrite specific fields
$dto->fill(['name' => 'Jane Doe']);
echo $dto->name; // Jane Doe

$dto1 = new SimpleDto()->setName('John Doe');
$dto2 = new SimpleDto()
    ->setAge('25')
    ->setAddress('Some address');

$dto3 = $dto1->merge($dto2);

// $dto3 now contains all fields from both DTOs
echo $dto3->getName();    // John Doe
echo $dto3->getAge();     // 25
echo $dto3->getAddress(); // Some address

$dto1 = new SimpleDto([
    'name' => 'John Doe',
    'age' => '25',
    'address' => 'Some address'
]);

$dto2 = new SimpleDto(['name' => 'Jane Doe']);

$diff = $dto1->diff($dto2);

/*
[
    'name' => ['old' => 'John Doe', 'new' => 'Jane Doe'],
    'age' => ['old' => '25', 'new' => null],
    'address' => ['old' => 'Some address', 'new' => null]
]
*/

$dto = new SimpleDto(['name' => 'John Doe']);
$clone = $dto->clone();

$diff = $dto->diff($clone); // Empty array - perfect copy

$dto = new SimpleDto([
    'name' => 'John Doe',
    'age' => '25'
]);

// To array
$array = $dto->toArray();

// To JSON
$json = $dto->toJson();

use YourVendor\Dto\NestedDto;
use YourVendor\Dto\SimpleDto;

$dto = new NestedDto([
    'children' => new SimpleDto([
        'name' => 'John Doe',
        'age' => '25',
        'address' => 'Some address'
    ]),
    'companyAddress' => 'Some address',
    'companyName' => 'google'
]);

// Access nested properties
$children = $dto->getChildren(); // Returns SimpleDto instance
echo $children->getName(); // John Doe

// Serialize nested DTOs
$array = $dto->toArray();
/*
[
    'children' => [
        'name' => 'John Doe',
        'age' => '25',
        'address' => 'Some address'
    ],
    'companyAddress' => 'Some address',
    'companyName' => 'google'
]
*/

// Merge nested DTOs
$dto1 = new NestedDto($data);
$dto2 = new NestedDto();
$dto2->setChildren(
    (new SimpleDto())
        ->setName('Changed name')
        ->setAge(null)
);

$merged = $dto1->merge($dto2);
echo $merged->getChildren()->getName(); // Changed name

use Forge\Dto\Support\BaseDto;
use Forge\Dto\Support\Validation\Uuid;
use Forge\Dto\Support\Validation\Required;
use Forge\Dto\Support\Validation\Inn;

final class UserDto extends BaseDto
{
    #[Uuid]
    public ?string $id = null;
    
    #[Required]
    public ?string $name = null;
    
    #[Inn]
    public ?string $inn = null;
}

// Validation happens automatically on property assignment
$dto = new UserDto();
$dto->setId('invalid-uuid'); // Throws DtoValidationException
$dto->setId('550e8400-e29b-41d4-a716-446655440000'); // ✅

$dto->setInn('627708638650'); // ✅ Valid individual INN
$dto->setInn('4404380820');   // ✅ Valid legal entity INN

$dto = new UserDto();

try {
    $dto->setId('invalid-uuid');
} catch (DtoValidationException $e) {
    // Exception thrown
}

// Validation errors are used by default value generators
if (empty($dto->getValidationErrors())) {
    // Safe to generate defaults
}

use Attribute;
use Forge\Dto\Contracts\PropertyValidatorInterface;
use Forge\Dto\Support\Validation\Traits\HasLaravelValidation;

#[Attribute(Attribute::TARGET_PROPERTY)]
readonly class Email implements PropertyValidatorInterface
{
    use HasLaravelValidation;

    public function validate(mixed $value, string $propertyName): void
    {
        $this->performValidation(
            value: $value,
            rules: ['nullable', 'email'],
            field: $propertyName
        );
    }
}

// Usage
final class ContactDto extends BaseDto
{
    #[Email]
    public ?string $email = null;
}

use Attribute;
use Forge\Dto\Contracts\DefaultValueGeneratorInterface;
use Forge\Dto\Support\BaseDto;

#[Attribute(Attribute::TARGET_PROPERTY)]
class UuidGenerator implements DefaultValueGeneratorInterface
{
    public function generate(BaseDto $dto): mixed
    {
        // return the generated value for the property
    }

    public function supports(BaseDto $dto, string $propertyName): bool
    {
        // return true if generation should occur (e.g. property is empty and DTO has no errors)
    }
}

// Usage
final class EntityDto extends BaseDto
{
    #[UuidGenerator]
    public ?string $id = null;
}

final class UserDto extends BaseDto
{
    public ?string $age = null; // declared as string
}

$dto = new UserDto()->setAge(25); // passing int
echo gettype($dto->getAge()); // "string" — automatically cast to match property type

use Forge\Dto\Support\BaseDto;
use Forge\Dto\Support\Casting\CastEachTo;

final class OrderDto extends BaseDto
{
    #[CastEachTo(LineItemDto::class)]
    public ?array $items = null;
}

$order = new OrderDto([
    'items' => [
        ['sku' => 'A-1', 'qty' => 2],
        ['sku' => 'B-7', 'qty' => 1],
    ],
]);

$order->items[0]; // LineItemDto instance

use Attribute;
use Forge\Dto\Contracts\PropertyMaskInterface;

#[Attribute(Attribute::TARGET_PROPERTY)]
readonly class MaskCard implements PropertyMaskInterface
{
    public function apply(string $value): string
    {
        return str_repeat('*', max(0, strlen($value) - 4)) . substr($value, -4);
    }
}

final class PaymentDto extends BaseDto
{
    #[MaskCard]
    public ?string $cardNumber = null;
}

$dto = new PaymentDto(['cardNumber' => '4111111111111111']);

$dto->toArray();              // ['cardNumber' => '4111111111111111']
$dto->toArray(masking: true); // ['cardNumber' => '************1111']
echo $dto->cardNumber;        // '4111111111111111' — untouched