PHP code example of phprise / data-transfer-object
1. Go to this page and download the library: Download phprise/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/ */
phprise / data-transfer-object example snippets
use Phprise\DataTransferObject\TransferObject;
class UserDto extends TransferObject
{
public string $name;
public int $age;
}
// Create from array
$data = ['name' => 'John Doe', 'age' => 30];
$dto = UserDto::fromArray($data);
echo $dto->name; // John Doe
echo $dto->age; // 30
// Convert back to array
$array = $dto->toArray();
// ['name' => 'John Doe', 'age' => 30]
class UserProfileDto extends TransferObject
{
public string $firstName;
public string $lastName;
}
$data = [
'first_name' => 'Alice',
'last_name' => 'Wonderland',
];
$dto = UserProfileDto::fromArray($data);
echo $dto->firstName; // Alice
// Export as snake_case array
$snakeArray = $dto->toSnakeCaseArray();
// ['first_name' => 'Alice', 'last_name' => 'Wonderland']
class AddressDto extends TransferObject
{
public string $street;
public string $city;
}
class CustomerDto extends TransferObject
{
public string $name;
public AddressDto $address;
}
$data = [
'name' => 'Bob',
'address' => [
'street' => '123 Maker Lane',
'city' => 'Buildtown',
],
];
$dto = CustomerDto::fromArray($data);
echo $dto->address->city; // Buildtown
class EventDto extends TransferObject
{
public string $title;
public \DateTimeImmutable $date;
}
$data = [
'title' => 'Conference',
'date' => '2023-10-27T10:00:00+00:00',
];
$dto = EventDto::fromArray($data);
echo $dto->date->format('Y-m-d'); // 2023-10-27