PHP code example of talanov / data-transfer

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

    

talanov / data-transfer example snippets


use Talanov\DataTransfer\Attributes\Cast;
use Talanov\DataTransfer\Casts\UppercaseCast;
use Talanov\DataTransfer\DataTransferObject;

final class AccountData extends DataTransferObject
{
    public string $name;
    
    #[Cast(UppercaseCast::class)]
    public string $currency;

    public ?string $iban = null;

    #[Cast('float', 0.0)]
    public ?float $balance = null;

    public ?string $description = null;
}

// From an array:
$account = new AccountData([
    'name' => 'My account',
    'currency' => 'EUR',
    'iban' => 'DE89370400440532013000',
    'balance' => '123.45',
    'description' => 'My first account',
]);

// Using named arguments:
$account = new AccountData(
    name: 'My account',
    currency: 'EUR',
    iban: 'DE89370400440532013000',
    balance: '123.45',
    description: 'My first account',
);

// From an object:
$source = (object) [
    'name' => 'My account',
    'currency' => 'EUR',
    'iban' => 'DE89370400440532013000',
    'balance' => '123.45',
    'description' => 'My first account',
];
$account = new AccountData($source);

// Using a static factory:
$account = AccountData::from([
    'name' => 'My account',
    'currency' => 'EUR',
    'iban' => 'DE89370400440532013000',
    'balance' => '123.45',
    'description' => 'My first account',
]);

use Talanov\DataTransfer\DataTransferObject;

final class PostData extends DataTransferObject
{
    public string $title;

    public string $slug;

    protected function init(): void
    {
        $this->slug = strtolower(str_replace(' ', '-', $this->title));
    }
}

$post = new PostData(title: 'Hello World');
echo $post->slug; // 'hello-world'