PHP code example of bfg / dto

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

    

bfg / dto example snippets


use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected array $hidden = [
        'password'
    ];
    
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);
// Or
$dto = UserDto::new(
    name: 'John Doe',
    email: '[email protected]',
    password: '123456'
);

echo $dto->name; // John Doe

$dto = UserDto::fromEmpty();

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

$dto = UserDto::fromAnything(['name' => 'John Doe', 'email' => '[email protected]']);
$dto = UserDto::fromAnything([
    ['name' => 'John Doe', 'email' => '[email protected]'],
    ['name' => 'John Doe', 'email' => '[email protected]'],
]);
$dto = UserDto::fromAnything(\Illuminate\Foundation\Http\FormRequest::class);
$dto = UserDto::fromAnything('{"name":"John Doe","email":"[email protected]"}');
$dto = UserDto::fromAnything('C:8:"UserDto":23:{a:2:{s:4:"name";s:8:"John Doe";s:5:"email";s:13:"[email protected]";}}');
$dto = UserDto::fromAnything(User::find(1));

$firstDto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

$secondDto = UserDto::fromDto($firstDto); 
// Creates a new DTO with the same properties as the first DTO

$fluent = (new \Illuminate\Support\Fluent([
    'name' => 'John Doe',
    'email' => '[email protected]',
]))->set('password', '123456');

$dto = UserDto::fromFluent($fluent);

UserDto::fromUrl(string $url, array|string|null $query = null, array $headers = []);
UserDto::fromUrl('https://test.dev');

$dto = UserDto::fromGet(string $url, array|string|null $query = null, array $headers = []);

UserDto::fromGet('https://test.dev', ['name' => 'John Doe', 'email' => '[email protected]']);

$dto = UserDto::fromPost(string $url, array $data = [], array $headers = []);

UserDto::fromPost('https://test.dev', ['name' => 'John Doe', 'email' => '[email protected]']);

$dto = UserDto::fromHttp(string $method, string $url, array|string|null $data = [], array $headers = []): DtoCollection|static|null;

UserDto::fromHttp('get', 'https://test.dev', ['name' => 'John Doe', 'email' => '[email protected]']);

$dto = UserDto::fromRequest(\Illuminate\Foundation\Http\FormRequest::class);

$dto = UserDto::fromJson('{"name":"John Doe","email":"[email protected]"}');

$dto = UserDto::fromSerialize('C:8:"UserDto":23:{a:2:{s:4:"name";s:8:"John Doe";s:5:"email";s:13:"[email protected]";}}');

$dto = UserDto::fromModel(User::find(1));

$dto = UserDto::fromStaticCache('user', function () {
    return UserDto::fromArray([
        'name' => 'John Doe',
        'email' => '[email protected]',
    ]);
});

$collection = UserDto::fromCollection([
    ['name' => 'John Doe', 'email' => '[email protected]'],
    ['name' => 'Sam Doe', 'email' => '[email protected]'],
]);

// You can cache dto before
$dto->cache();

$dto = UserDto::fromCache(function () {
    // If cache not found
    return UserDto::fromArray([
        'name' => 'John Doe',
        'email' => '[email protected]',
    ]);
});

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
    
    public static function sourceV1(...$arguments): array {
    
        // Do something
    
        return [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => '123456',
        ];
    }
}

$dto = UserDto::fromSource('v1', ...$arguments);

use Bfg\Dto\Dto;

class AddressDto extends Dto
{
    public function __construct(
        public string $city,
        public string $street,
    ) {}
}

class CommentDto extends Dto
{
    public function __construct(
        public string $message,
    ) {}
}

class UserDto extends Dto
{
    protected array $hidden = [
        'password'
    ];
        
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        public AddressDto $address,
        public CommentDto|array $comments,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
    'address' => [
        'city' => 'New York',
        'street' => 'Wall Street',
    ],
    'comments' => [
        ['message' => 'The first comment'],
        ['message' => 'The second comment'],
    ]
]);

echo $dto->address->city; // New York
// And
foreach ($dto->comments as $comment) {
    echo $comment->message;
}

use Bfg\Dto\Dto;
use App\Models\User;
use Bfg\Dto\Attributes\DtoName;

class UserDto extends Dto
{
    public function __construct(
        public string $name,
        public string $email,
        #[DtoName('user_id')] 
        public ?User $user,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'user_id' => 1,
    // Or 
    'user' => 1, 
]);

dump($dto->user); // User model
// In Array you will get the id of the model
dump($dto->toArray()); // ['name' => 'John Doe', 'email' => '[email protected]', 'user_id' => 1]

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    public function __construct(
        public string $name,
        public string $email,
        public \Carbon\Carbon $created_at,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'created_at' => '2025-01-01 00:00:00',
]);

dump($dto->created_at); // Carbon object
// In Array you will get the date in the format `Y-m-d H:i:s`
dump($dto->toArray()); // ['name' => 'John Doe', 'email' => '[email protected]', 'created_at' => '2025-01-01 00:00:00']

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    public function __construct(
        public string $email,
        public ?string $password,
    ) {}
}

class SpecialUserDto extends UserDto
{
    protected static array $extends = [
        'name' => 'string|null',
        // Or
        'name' => ['string', 'null'],
    ];
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected static array $casts = [
        'is_admin' => 'bool',
        'created_at' => 'datetime',
    ];
        
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        public bool $is_admin,
        public \Carbon\Carbon $created_at,
    ) {}
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected static array $casts = [
        'is_admin' => 'bool',
        'created_at' => 'datetime',
        'name' => UserNameCast::class,
    ];
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected static array $casts = [
        'is_admin' => 'bool',
        'created_at' => 'datetime',
        'name' => UserNameCast::class,
        'status' => UserStatusEnum::class,
    ];
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected array $hidden = [
        'password'
    ];
            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
]);

echo $dto->toArray(); // ['name' => 'John Doe', 'email' => '[email protected]']

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected static array $rules = [
        'name' => 'otected static array $ruleMessages = [
        'name.   public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
]); // Throws an exception

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected array $encrypted = [
        'password'
    ];
                
    public function __construct(
        public string $name,
        public string $email,
        public string $password, // Data will be decrypted
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => \Illuminate\Support\Facades\Crypt::encrypt('123456'),
]);

echo $dto->password; // You will get decrypted password

dump($dto->toArray()); // ['name' => 'John Doe', 'email' => '[email protected]', 'password' => 'encrypted data']

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
    
    protected function fromArrayName(string $name): string
    {
        return ucwords($name);
    }

    protected function toArrayName(string $name): string
    {
        return strtolower($name);
    }
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $lastName,
        public string $email,
        public ?string $password,
    ) {}
        
    public function fullName(): string
    {
        return $this->name . ' ' . $this->lastName;
    }
}

$dto = UserDto::fromArray([
    'name' => 'John',
    'lastName' => 'Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->fullName; // John Doe

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $lastName,
        public string $email,
        public ?string $password,
    ) {}
        
    public function fullName(): string
    {
        return $this->name . ' ' . $this->lastName;
    }
}

$dto = UserDto::fromArray([
    'name' => 'John',
    'lastName' => 'Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->lazyEmail; // [email protected]
echo $dto->lazyFullName; // John Doe, and it put in the cache
$dto->set('name', 'Sam');
echo $dto->lazyFullName; // John Doe, because it is taken from the cache

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
]);

echo $dto->name(); // John Doe
// The same as
echo $dto->get('name'); // John Doe

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
    
    public static function defaultName()
    {
        return 'Jon';
    }
}

$dto = UserDto::fromArray([
    'email' => '[email protected]',
    'password' => '123456',
]);

echo $dto->name; // Jon

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        public AddressDto|array $address,
        // Or
        public AddressDto|\Illuminate\Support\Collection $address,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
    'address' => [
        ['city' => 'New York', 'street' => 'Wall Street'],
        ['city' => 'Los Angeles', 'street' => 'Hollywood Street'],    
    ]
]);

foreach ($dto->address as $address) {

    echo $address->city;
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $lastName,
        public string $email,
        public ?string $password,
    ) {}
        
    public function withFullName(): string
    {
        return $this->name . ' ' . $this->lastName;
    }
}

$dto = UserDto::fromArray([
    'name' => 'John',
    'lastName' => 'Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

dump($dto->toArray()); // ['name' => 'John', 'lastName' => 'Doe', 'email' => '[email protected]', 'password' => '123456', 'fullName' => 'John Doe']

use Bfg\Dto\Dto;

class UserDto extends Dto
{
    protected static bool $logsEnabled = true;
    
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
]);

$dto->set('name', 'Sam Doe');

dump($dto->logs()); // You will get logs DTO

$dto->log(string $message, array $context = []);

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
]);

$dto->setMeta(['key' => 'value']);
$dto->setMeta(['key2' => 'value2']);
echo $dto->getMeta('key'); // value
echo $dto->getMeta('key2'); // value2
// You can get all meta
dump($dto->getMeta()); // ['key' => 'value', 'key2' => 'value2']
// You can remove meta
$dto->unsetMeta('key');

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        #[\Bfg\Dto\Attributes\DtoItem(UserContactDto::class)]
        public \Bfg\Dto\Collections\DtoCollection $contacts,
    ) {}
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        #[DtoName('user')] 
        public string $name,
        public string $email,
        public ?string $password,
    ) {}
}

$dto = UserDto::fromArray([
    'user' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);
// Or
$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->name; // John Doe

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    #[DtoName('user', 'name')]
    protected static array $extends = [
        'name' => 'string',
    ];

    public function __construct(
        public string $email,
        public ?string $password,
    ) {}
}

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        #[DtoFromConfig('app.name')]
        public string $appName,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->appName; // Laravel

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        #[DtoFromRequest]
        public string $id,
    ) {}
}

// https://test.dev/?id=100

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->id; // 100

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        #[DtoFromRoute]
        public string $id,
    ) {}
}

// Route::get('/{id}', function ($id) {});

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->id; // 100

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        
        #[DtoFromCache('user')]
        public string $userFromCache,
        // Or
        #[DtoFromCache]
        public string $user,
    ) {}
}

Cache::put('user', 'John Doe', 60);

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456'
]);

echo $dto->user; // John Doe

use Bfg\Dto\Dto;

class UserDto extends Dto
{            
    public function __construct(
        public string $name,
        public string $email,
        public ?string $password,
        #[DtoToResource(UserAddressResource::class)]
        public AddressDto $address,
    ) {}
}

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
    'password' => '123456',
    'address' => [
        'city' => 'New York',
        'street' => 'Wall Street',
    ]
]);

echo $dto->toArray(); 
// ['name' => 'John Doe', 'email' => '...', 'password' => '...', 'address' => ['city' => 'New York', 'street' => 'Wall Street']]

UserDto::on('creating', function (array $arguments) {
    $arguments['name'] = 'John Doe';
    return $arguments;
});

UserDto::on('created', function (UserDto $dto, array $arguments) {
    $dto->name = 'John Doe';
});

UserDto::on(['updating', 'name'], function (mixed $value, UserDto $dto) {
    return strtoupper($value);
});

UserDto::on(['updated', 'name'], function (UserDto $dto) {
    $dto->name = strtoupper($dto->name);
});

UserDto::on(['mutating', 'name'], function (mixed $value, UserDto $dto, array $arguments) {
    return strtoupper($value);
});

UserDto::on(['mutated', 'name'], function (mixed $value, UserDto $dto, array $arguments) {
    return strtoupper($value);
});

UserDto::on('serialize', function (array $arguments, UserDto $dto) {
    $arguments['name'] = strtoupper($arguments['name']);
    return $arguments;
});

UserDto::on('unserialize', function (array $arguments, UserDto $dto) {
    $arguments['name'] = strtolower($arguments['name']);
    return $arguments;
});

UserDto::on('clone', function (array $arguments, UserDto $dto) {
    $arguments['name'] = strtolower($arguments['name']);
    return $arguments;
});

UserDto::on('fromModel', function (UserDto $dto, array $arguments) {
    // You can change the DTO data or something else
});

UserDto::on('fromEmpty', function (UserDto $dto, array $arguments) {
    // You can change the DTO data or something else
});

UserDto::on('fromArray', function (UserDto $dto, array $arguments) {
    // You can change the DTO data or something else
});

UserDto::on('fromRequest', function (UserDto $dto, array $arguments) {
    // You can change the DTO data or something else
});

UserDto::on('fromJson', function (UserDto $dto, array $arguments) {
    // You can change the DTO data or something else
});

UserDto::on('fromJson', function (UserDto $dto) {
    // You can change the DTO data or something else
});

UserDto::on('prepareModel', function (array $arguments) {
    $arguments['name'] = 'John Doe';
    return $arguments;
});

UserDto::on('prepareSerialize', function (string $serializedString) {
    // You can change the serialized string or something else
    return $serializedString;
});

UserDto::on('prepareJson', function (array $arguments) {
    // You can change the json array or something else
    return $arguments;
});

UserDto::on('prepareRequest', function (array $arguments) {
    // You can change the request array or something else
    return $arguments;
});

UserDto::on('prepareArray', function (array $arguments) {
    // You can change the array or something else
    return $arguments;
});

UserDto::on('prepareEmpty', function () {
    // You can create a new array or something else
    return [];
});

UserDto::on('destruct', function (UserDto $dto) {
    // You can do something with the DTO
});

$dto->explain();

$dto->vars();

$dto->getModifiedFields();

$dto->getRelationNames();

$dto->getPropertyNames();

$dto->getNames();

$dto->getReflection();

$dto->toArray();

$dto->toJson($options = 0);

$dto->toResponse(int $status = 200, array $headers = [], int $options = 0);

$dto->toCollection();

$dto->toBase64();

$dto->toModel(User::class);

$dto->toSerialize();

$dto->toApi(string $url, string $method = 'post', array $headers = []);

$dto->toString();
//Or
echo (string) $dto;

$dto->toFluent();

$dto->toImport(string $fileName, string $sheetName = 'Sheet1', array $options = []);

$dto->toUrl(string|null $baseUrl = null, array $exclude = [], array $only = [], array $query = []): string;

$dto = UserDto::fromArray([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);
// Generate only url parameters
echo $dto->toUrl();
// ?name=John%20Doe&email=test%40gmail.com

// Or generate parameters with base url
echo $dto->toUrl('https://example.com');
// https://example.com?name=John%20Doe&email=test%40gmail.com  

// Or generate parameters with base url but without email property
echo $dto->toUrl('https://example.com', exclude: ['email']); 
// https://example.com?name=John%20Doe

// Or generate parameters with base url use only email property
echo $dto->toUrl('https://example.com', only: ['email']);
// https://example.com?email=test%40gmail.com

// Or generate parameters with base url and additional query parameters
echo $dto->toUrl('https://example.com', query: ['page' => 1]);
// https://example.com?name=John%20Doe&email=test%40gmail.com&page=1

// And you can use parameters like tags in the base url
echo $dto->toUrl('https://example.com/find/{name}/name');
// https://example.com/find/John%20Doe/name?email=test%40gmail.com

// And you can convert DTO to the route.
// For example, you can have a route named 'user.profile'.
// You can use the `toUrl` method to generate a URL for that route.
echo $dto->toUrl('user.profile');
// This will generate a URL like: https://example.com/user/profile?name=John%20Doe&email=test%40gmail.com

$collection = UserDto::fromCollection([
    ['name' => 'John Doe', 'email' => '[email protected]', 'password' => '123456'],
    ['name' => 'Sam Doe', 'email' => '[email protected]', 'password' => '123456'],
]);

$collection->insertToDatabase('users');

$collection = UserDto::fromCollection([
    ['name' => 'John Doe', 'email' => '[email protected]', 'password' => '123456'],
    ['name' => 'Sam Doe', 'email' => '[email protected]', 'password' => '123456'],
]);

$collection->insertToModel(\App\Models\User::class);

UserDto::new(
    name: 'John Doe',
    email: '[email protected]',
    password: '123456',
);

UserDto::version();

$dto->pipeline([
    SomeClassForPipeline::class,
]);

$dto->camelKeys()->toArray();

$dto->snakeKeys()->toArray();
bash
php artisan make:dto UserDto
bash
php artisan make:dto-cast UserNameCast
bash
php artisan make:enum UserStatusEnum
bash
php artisan make:resource UserAddressResource
bash
php artisan make:dto UserDto
bash
php artisan make:dto-cast UserNameCast
bash
php artisan make:dto-docs
json
"scripts": {
    "post-autoload-dump": [
        "@php artisan make:dto-docs"
    ],
}
php
$dto->cache(\DateTimeInterface|\DateInterval|int|null $ttl = null);
php
$dto->cacheKey('name');
php
$dto->getCachedKey('name');
php
$dto->cacheKeyClear('name');
php
$dto->restore();
php
$dto->originals();
php
$dto->count();
php
$dto->has('name');
php
isset($dto['name']);
php
$dto->dataHash();
php
$dto->hash();
php
$dto->clone();
php
$dto->str('name')->camel()->snake();
php
$dto->collect('addresses')->map(function (UserAddressDto $address) {
    return $address->city;
});
php
$dto->boolable('confirmed');
php
$dto->toggleBool('is_admin');
php
$dto->increment('count');
php
$dto->decrement('count');
php
$dto->set('name', 'John Doe');
php
$dto->get('name');
php
$dto->map(function (mixed $value, string $key) {
    return strtoupper($value);
});
php
$dto->isEmpty('name');
php
$dto->isNotEmpty('name');
php
$dto->isNull('name');
php
$dto->isNotNull('name');
php
$dto->isCanNull('name');
php
$dto->isTrue('is_admin');
php
$dto->isFalse('is_admin');
php
$dto->isBool('is_admin');
php
$dto->isEquals('name', 'John Doe');
php
$dto->isNotEquals('name', 'John Doe');
php
$dto->isInstanceOf('address', AddressDto::class);
php
$dto->isNotInstanceOf('address', AddressDto::class);
php
$dto->isString('name');
php
$dto->isNotString('name');
php
$dto->isInt('id');
php
$dto->isNotInt('id');
php
$dto->isFloat('price');
php
$dto->isNotFloat('price');
php
$dto->isArray('addresses');
php
$dto->isNotArray('addresses');
php
$dto->isObject('address');
php
$dto->isNotObject('address');
php
$dto->isInstanceOfArray('addresses', AddressDto::class);
php
$dto->isNotInstanceOfArray('addresses', AddressDto::class);