PHP code example of antwerpes / data-transfer-object

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

    

antwerpes / data-transfer-object example snippets


use Antwerpes\DataTransferObject\Attributes\Cast;
use Antwerpes\DataTransferObject\Attributes\Map;
use Antwerpes\DataTransferObject\Casts\ArrayCaster;
use Antwerpes\DataTransferObject\DataTransferObject;

class User extends DataTransferObject
{
    public function __construct(
        public string $name;
        #[Cast(CustomDateCaster::class)]
        public DateTimeInterface $birthday;
        #[Map(from: 'address.city')]
        public string $city;
        #[Cast(ArrayCaster::class, itemType: Interest:class)]
        public array $interests;
    ) {}
}

$json = '{
    "name": "John Doe",
    "birthday": "1990-01-01",
    "address": {
        "city": "New York"
    },
    "interests": [
        {
            "name": "Music"
        },
        {
            "name": "Programming"
        }
    ]
}';
$user = User::decode(json_decode($json, true));
$encoded = $user->encode();

use Antwerpes\DataTransferObject\CastsProperty;

class CustomDateCaster implements CastsProperty
{
    public function unserialize(mixed $value): DateTimeInterface
    {
        return new DateTime($value);
    }
    
    public function serialize(mixed $value): string
    {
        return $value->format('Y-m-d');
    }
}

use Antwerpes\DataTransferObject\Attributes\Map;

class User extends DataTransferObject
{
    #[Map(from: 'address.city', to: 'address.city')]
    public string $city;
}