PHP code example of adventure-tech / data-transfer-object
1. Go to this page and download the library: Download adventure-tech/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/ */
adventure-tech / data-transfer-object example snippets
$dto = MyDTO::from($source);
use AdventureTech\DataTransferObject\DataTransferObject;
use Carbon\Carbon;
class User extends DataTransferObject
{
public int $id;
public string $first_name;
public string $last_name;
public string $email;
public Carbon $created_at;
public Carbon $deleted_at;
}
#[MapFrom('first_name')]
public string $firstName;
#[DefaultValue(false)]
public bool $isAdmin;
// The DTO will look for the created_at property on the source, and cast it to Carbon
#[MapFrom('created_at')]
public Carbon $createdAt;
// The source property value can be true/false or 0/1
public bool $isPaid;
// The main DTO
class Person extends DataTransferObject
{
#[MapFrom('first_name')]
public string $firstName;
#[JsonMapper(Address::class)]
public Address $address;
}
// The Address POPO
class Address
{
public string $street;
public string $zip;
public string $city;
}
// The enum value from the database will be mapped to the correct enum value.
public MyEnum $myEnum;
#[Immutable]
public string $weCanPretendThisIsImmutable;
class User extends DataTransferObject
{
#[MapFrom('first_name')]
public string $firstName;
#[MapFrom('last_name')]
public string $lastName;
#[Trigger('setFullName')]
public string $fullName;
protected function setFullName()
{
$this->fullName = $this->firstName . ' ' . $this->lastName;
}
}
use AdventureTech\DataTransferObject\Attributes\DefaultValue;
use AdventureTech\DataTransferObject\Attributes\MapFrom;
use AdventureTech\DataTransferObject\Attributes\Optional;
use AdventureTech\DataTransferObject\DataTransferObject;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use stdClass;
class User extends DataTransferObject
{
public int $id;
#[MapFrom('first_name')]
public string $firstName;
#[MapFrom('last_name')]
public string $lastName;
public string $email;
#[MapFrom('created_at')]
public Carbon $createdAt;
#[MapFrom('deleted_at')]
public Carbon $deletedAt;
#[Optional]
public string $iAmNotImportant;
// Relations
#[DefaultValue([])]
public array $posts;
}