Skip to content

Examples

Greg Bowler edited this page Jun 20, 2023 · 2 revisions

1. Build an object up and convert it to JSON

use Gt\DataObject\DataObject;

$obj = (new DataObject())
	->with("name", "Cody")
	->with("colour", "orange")
	->with("food", [
		"biscuits",
		"mushrooms",
		"corn on the cob",
	]);

echo json_encode($obj), PHP_EOL;

Output:

{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}

2. Build a DataObject from a JSON string

use Gt\DataObject\DataObjectBuilder;

$jsonString = '{"name":"Cody","colour":"orange","food":["biscuits","mushrooms","corn on the cob"]}';

$builder = new DataObjectBuilder();
$obj = $builder->fromObject(json_decode($jsonString));

echo "Hello, ",
	$obj->getString("name"),
	"! Your favourite food is ",
	$obj->getArray("food")[0],
	PHP_EOL;

Output:

Hello, Cody! Your favourite food is biscuits

3. Type casting

use Gt\DataObject\DataObject;

require __DIR__ . "/../vendor/autoload.php";

// Set an object with all string values, similar to a web requests:
$obj = new DataObject();
$obj = $obj->with("one", "1");
$obj = $obj->with("two", "two");
$obj = $obj->with("pi", "3.14159");

// Automatically cast to int:

$int1 = $obj->getInt("one");
$int2 = $obj->getInt("two");
$int3 = $obj->getInt("pi");

echo "One: $int1, two: $int2, three: $int3", PHP_EOL;

Output:

One: 1, two: 0, three: 3

Note how the decimal data is lost in the cast to int, but how the original data is not lost.

4. Type safety within arrays

use Gt\DataObject\DataObject;

$obj = new DataObject();
$obj = $obj->with("arrayOfData", [
	1,
	2,
	3.14159
]);

echo "The first element in the array is: ",
	$obj->getArray("arrayOfData", "int")[0], // note the type check of "int"
	PHP_EOL;

Output:

The first element in the array is: PHP Fatal error:  Uncaught TypeError: Array index 2 must be of type int, double given