Simple library for encoding and decoding JSON structures into PHP objects, e.g. to work with API responses in a strongly typed way.
You can install the package via composer:
composer require antwerpes/data-transfer-object
Define a class that extends Antwerpes\DataTransferObject\DataTransferObject
and define the structure of the object:
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,
) {}
}
Then you can use the class to decode JSON strings into PHP objects:
$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();
You can define custom casters by implementing the Antwerpes\DataTransferObject\CastsProperty
interface:
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');
}
}
You can map nested properties to a flat structure using the Map
attribute:
use Antwerpes\DataTransferObject\Attributes\Map;
class User extends DataTransferObject
{
public function __construct(
#[Map(from: 'address.city', to: 'address.city')]
public string $city,
) {}
}
Validation is out of scope for this package, use JSON schemas or other libraries like symfony/validator
to validate the object.
Please see CHANGELOG for more information on what has changed recently.
Contributions are welcome! Leave an issue on GitHub, or create a Pull Request.
The MIT License (MIT). Please see License File for more information.