vanengers / php-json-object-library
API 的基础类
v1.2
2023-12-05 12:15 UTC
Requires
- php: >=7.0.0
- ext-json: *
Requires (Dev)
- phpunit/phpunit: 10.5.x-dev
README
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']);
或直接传递 Json
$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;
}
}
将 json/array 数据转换为另一个对象的属性
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"
序列化为 json / 创建数组
$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']]);
仅当值为 null 时跳过对象中的某些字段进行序列化
$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';
...
}
结果如下
{
"property2": "value"
}
当结果集定义了具有相同键的多维数组时,添加前缀到您的键
然后您可以处理父键名并在映射器中添加整个键
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"
}
}
在解析 json 时应使用前缀选项并使用设置器
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);
}
}
}