This is a helper to add attributes to an array. This will help,
if you need to represent JSON entities / classes and resolve recursively when JSON encoding.
composer require probiers-us/php-json-property
You can use JsonPropertyInterface
and JsonPropertyTrait
in the classes
you want to add this. Calling json_encode
will recursively resolve all embedded
classes in the JSON properties array, leveraging JsonSerializable
.
$jsonPropertyClass->addJsonProperty('key', 'value');
$jsonPropertyClass->addJsonProperties(['key', 'value']);
$jsonPropertyClass->removeJsonProperty('key');
$jsonPropertyClass->setJsonProperties(['key', 'value']);
Get the array without resolving embedded properties
$jsonPropertyClass->getJsonProperties();
Get the array of properties and resolve embedded
$jsonPropertyClass->getJsonProperties(true);
To add typed JSON properties, add a wrapper around e.g. addJsonProperty
public function addName(string $name) {
$this->addJsonProperty('name', $name);
}