Skip to content
Greg Bowler edited this page Mar 28, 2023 · 6 revisions

Throughout PHP.Gt libraries, wherever an object is used to represent data, the PHP.Gt/DataObject library is used. Instances of DataObject provide structured, type-safe, immutable data transfer.

This library extends DataObject by adding JSON-specific functionality. The main usage will be via the JsonObjectBuilder class that can be used to build a type of JsonObject from any JSON string or decoded JSON object from json_decode.

The purpose of using these classes to represent decoded JSON data is to provide a type-safe, immutable interface to the enclosed data. What is immutability?

A typical example

The following JSON string is taken from the Stripe API documentation as example data to work with.

$jsonString:

{
	"object": "balance",
	"available": [
		{
			"amount": 2217713,
			"currency": "cad",
			"source_types": {
				"bank_account": 0,
				"card": 2217713
			}
		},
		{
			"amount": 7254790,
			"currency": "gbp",
			"source_types": {
				"bank_account": 0,
				"card": 7254790
			}
		}
	]
}

For our example, we will output the value of the object key, and then iterate over the available array, outputting the amount and currency contained within the objects.

$builder = new JsonObjectBuilder();
$json = $builder->fromJsonString($jsonString);

echo "Type of object: ", $json->getString("object"), PHP_EOL;

/** @var JsonObject $available */
foreach($json->getArray("available") as $available) {
	echo PHP_EOL;
	echo "Currency: ", $available->getString("currency"), PHP_EOL;
	echo "Amount: ", number_format($available->getInt("amount") / 100), PHP_EOL;
}

Internally, the string is parsed with json_decode as usual, but the objects that are created are typed according to the data they represent, and have type-safe getters.


In the next section we will list out the type-safe getters and how to use them.

Clone this wiki locally