Base object for api
composer require vanengers/php-json-object-library
use Vanengers\PhpJsonObjectLibrary\PhpJsonObject;
class SamplePhpObject extends PhpJsonObject
{
public string $property = 'value';
}
$object = new SamplePhpObject(['property' => 'new value']);
$object = new SamplePhpObject("{\"property\":\"new value\"}");
class SamplePhpObject extends PhpJsonObject
{
public string $property = 'value';
public function setProperty(string $data): self
{
$this->property = $value;
// do stuff here like parsing data, transformation or validations
return $this;
}
}
class SamplePhpObject extends PhpJsonObject
{
public $mappers = [
'property_other_remote_name' => 'property'
];
public string $property = 'value';
...
}
$object = new SamplePhpObject("{\"property_other_remote_name\":\"new value\"}");
$object->getProperty(); // returns: "new value"
$object = new SamplePhpObject("{\"property\":\"new value\"}");
$array = $object->toArray();
$json = $object->toJson();
$object = new SamplePhpObject("{\"property\":\"new value\"}");
$array = $object->toArray(['skip' => ['property']]);
$json = $object->toJson(['skip' => ['property']]);
$object = new SamplePhpObject("{\"property\":\"new value\"}");
$array = $object->toArray(['skip' => ['property']]);
$json = $object->toJson(['skip' => ['property']]);
$object = new SamplePhpObject("{\"property\":\"new value\"}");
$array = $object->toArray(['skip_null' => ['property']]);
$json = $object->toJson(['skip_null' => ['property']]);
$object = new SamplePhpObject("{\"property\":\"new value\"}");
$array = $object->toArray(['skip_empty' => ['property']]);
$json = $object->toJson(['skip_empty' => ['property']]);
class SamplePhpObject extends PhpJsonObject
{
public $exclude_from_array = [
'property'
];
public string $property = 'value';
public string $property2 = 'value';
...
}
Which results in
{
"property2": "value"
}
Add prefixes to your keys, when your resultset defines multidimensional arrays with some keys being the same
class SamplePhpObject extends PhpJsonObject
{
public $mappers = [
'person_name' => 'author',
'recipient_name' => 'recipient',
];
public string $author = '';
public string $recipient = '';
...
}
{
"person": {
"name": "John Doe"
},
"recipient": {
"name": "Jane Doe"
}
}
class SamplePhpObject extends PhpJsonObject
{
public $mappers = [
'person_name' => 'author',
'recipient_name' => 'recipient',
];
public string $author = '';
public string $recipient = '';
public function setPerson($data)
{
if (is_array($data)) {
$this->fromArray($data);
}
}
public function setRecipient($data)
{
if (is_array($data)) {
$this->fromArray($data);
}
}
}