Quick start
In this guide we will install phpgt/dataobject, create a DataObject directly, then build one from an existing PHP structure.
[!NOTE] In WebEngine, this package is already present as a dependency, so you can use
GT\DataObject\DataObjectandGT\DataObject\DataObjectBuilderdirectly from your page logic or application classes.
1. Install the package
composer require phpgt/dataobject
2. Create a DataObject directly
The simplest way to start is to create an empty object and add keys with with():
use GT\DataObject\DataObject;
$product = new DataObject()
->with("name", "Notebook")
->with("price", 7.99)
->with("inStock", true);
DataObject is immutable, so with() does not modify the existing instance. It returns a new one with the extra key.
3. Read values back out
echo $product->getString("name"), PHP_EOL;
echo $product->getFloat("price"), PHP_EOL;
echo $product->getBool("inStock") ? "yes" : "no", PHP_EOL;
The typed getters cast or convert where it makes sense:
getString()casts scalars to stringsgetInt()casts strings, floats and booleans to integersgetFloat()casts strings, integers and booleans to floatsgetBool()casts common PHP scalar values to booleansgetDateTime()converts strings, integers and floats toDateTimeImmutable
4. Build from an associative array
If the data already exists in PHP, use DataObjectBuilder:
use GT\DataObject\DataObjectBuilder;
$builder = new DataObjectBuilder();
$product = $builder->fromAssociativeArray([
"id" => 105,
"name" => "Notebook",
"tags" => ["stationery", "paper"],
"supplier" => [
"name" => "Northwind",
"country" => "UK",
],
]);
Associative arrays are turned into nested DataObject instances. Indexed arrays stay as arrays.
5. Build from an object
The same builder can work from a plain object:
$source = new StdClass();
$source->id = 105;
$source->name = "Notebook";
$source->supplier = new StdClass();
$source->supplier->name = "Northwind";
$product = $builder->fromObject($source);
echo $product->getObject("supplier")?->getString("name");
At this point we have the shape of the library: build an immutable object once, then pass it around safely.
Next, move on to Building to see exactly how arrays, objects, nesting and builder errors behave.