xp-forge / marshalling
序列化
v2.2.0
2024-03-24 12:15 UTC
Requires
- php: >=7.0.0
- xp-framework/core: ^12.0 | ^11.0 | ^10.0 | ^9.0 | ^8.0 | ^7.0
- xp-framework/reflection: ^3.0 | ^2.0
Requires (Dev)
- xp-framework/test: ^2.0 | ^1.0
README
Marshalling可以将对象转换为映射,反之亦然。
示例
所有原始类型、数组及其映射都按原样生成
use util\data\Marshalling; $m= new Marshalling(); $m->marshal('Test'); // "Test" $m->marshal([1, 2, 3]); // [1, 2, 3] $m->marshal(['admin' => true]); // ["admin" => true]
值对象使用字段 => getter 查找进行序列化;支持 字段命名的方法 和 getField 习惯用法。
use util\data\Marshalling; class Person { private $name, $age; public function __construct(string $name, int $age) { $this->name= $name; $this->age= $age; } public function name(): string { return $this->name; } public function age(): int { return $this->age; } } $m= new Marshalling(); $m->marshal(new Person('...', 42)); // ["name" => "...", "age" => 42]
从映射反序列化时,将类型作为第二个参数传递。对象通过直接设置字段或使用 setField 习惯用法创建,而不调用构造函数。
use util\data\Marshalling; $m= new Marshalling(); $person= $m->unmarshal(['name' => '...', 'age' => 42], Person::class);
处理 "util" 包中的类型
use util\data\Marshalling; use util\{Date, Bytes, Money}; $m= new Marshalling(); $m->marshal(Date::now()); // "2018-08-29T10:40:49+0200" (ISO 8601) $m->marshal(new Bytes("\x50\x4b\x03\x04")); // "UEsDBA==" (base64) $m->marshal(new Money(12.99, $currency)); // ["amount" => 12.99, "currency" => "EUR"]
另请参阅