Converting
There are two common reasons to convert a DataObject back out again:
- a caller expects an array or plain object
- one key contains an array and you want to read it with fixed element types
getArray()
Use getArray() to read an array value:
use GT\DataObject\DataObject;
$report = new DataObject()
->with("scores", ["1", "2", "3.5"]);
$scores = $report->getArray("scores");
If the key is missing, getArray() returns null.
If the stored value is a nested DataObject, getArray() first converts it with asArray().
Fixed-type arrays
Pass a second argument to cast or validate each element:
use GT\DataObject\DataObject;
$report = new DataObject()
->with("scores", ["1", "2", "3.5"]);
$scores = $report->getArray("scores", "int");
var_dump($scores); // [1, 2, 3]
For built-in primitive checks, each element is cast individually. Common examples are:
"int""float""bool""string"
Class and interface names work too:
use DateTimeImmutable;
use DateTimeInterface;
use GT\DataObject\DataObject;
$dates = new DataObject()
->with("dates", [
new DateTimeImmutable("2024-01-01"),
new DateTimeImmutable("2024-02-01"),
]);
$typedDates = $dates->getArray("dates", DateTimeInterface::class);
When a class or interface name is used, values are not cast. They must already be instances of the requested type, otherwise TypeError is thrown.
Passing a type name that does not exist also throws TypeError.
asArray()
asArray() returns the whole object as a PHP array:
use GT\DataObject\DataObject;
$user = new DataObject()
->with("name", "Ada")
->with("address", (new DataObject())->with("town", "Leeds"));
print_r($user->asArray());
Nested DataObject instances are converted recursively.
asObject()
asObject() performs the same recursive conversion, but returns a plain object graph:
$userObject = $user->asObject();
echo $userObject->address->town;
JSON serialisation
DataObject implements JsonSerializable, and jsonSerialize() delegates to asArray():
echo json_encode($user), PHP_EOL;
That means a nested DataObject becomes nested JSON objects and arrays in the final output.
Next, have a look at Examples for a few complete patterns you can adapt in your own project.