Examples
This page collects a few small complete examples.
1. Build a DTO and serialise it to JSON
use GT\DataObject\DataObject;
$user = (new DataObject())
->with("id", 105)
->with("name", "Cody")
->with("roles", ["author", "editor"]);
echo json_encode($user), PHP_EOL;
Output:
{"id":105,"name":"Cody","roles":["author","editor"]}
2. Start from decoded JSON
use GT\DataObject\DataObjectBuilder;
$json = <<<'JSON'
{
"name": "Cody",
"address": {
"town": "Leeds"
},
"food": [
"biscuits",
"mushrooms"
]
}
JSON;
$builder = new DataObjectBuilder();
$user = $builder->fromObject(json_decode($json));
echo $user->getString("name"), PHP_EOL;
echo $user->getObject("address")?->getString("town"), PHP_EOL;
echo $user->getArray("food")[0], PHP_EOL;
3. Remove private fields before passing data on
use GT\DataObject\DataObject;
$user = (new DataObject())
->with("name", "Cody")
->with("email", "cody@example.com")
->with("creditCard", "4111 1111 1111 1111");
$shippingCopy = $user->without("creditCard");
$user still contains the original data. $shippingCopy is a separate immutable object without the sensitive key.
4. Cast each element of an array
use GT\DataObject\DataObject;
$scores = (new DataObject())
->with("scores", ["1", "2", "3.14159"]);
$wholeNumbers = $scores->getArray("scores", "int");
print_r($wholeNumbers);
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
5. Build a custom subclass from an object
use GT\DataObject\DataObject;
use GT\DataObject\DataObjectBuilder;
class UserData extends DataObject {}
$source = (object)[
"name" => "Cody",
"profile" => (object)[
"town" => "Leeds",
],
];
$builder = new DataObjectBuilder();
$user = $builder->fromObject($source, UserData::class);
Both $user and $user->getObject("profile") will be instances of UserData.