sparkcentral / marshaller
通用序列化组件。提供将数据从一种形式转换为另一种形式以及反之的功能。
dev-master
2015-08-04 06:02 UTC
Requires
- php: >=5.6.0
Requires (Dev)
- phpunit/phpunit: ^4.0
This package is not auto-updated.
Last update: 2024-09-14 17:37:22 UTC
README
通用序列化组件。提供将数据从一种形式转换为另一种形式以及反之的功能。
序列化在许多场景中非常有用。尽管如此,大多数场景都是关于获取对象的全部属性快照并将其发送到外部系统(持久化的数据库或HTTP响应体)。
通常,这种“源”数据不能直接发送,需要进行转换。在非常简单的情况下:您的对象属性可能使用“camelCase”样式命名,而您的数据库表字段名使用“下划线分隔”。实际上,有许多其他原因需要此类或类似的转换。
Marshaller 提供了一个简单的框架,用于在“源”和“目标”格式之间转换数据。
特性
- 支持双向转换(序列化/反序列化)
- 灵活定义模式,具有数据转换规则
- 支持不同的输入和输出格式。内置支持数组和非标准对象。
依赖项
- PHP >= 5.6.0
基本示例
<?php // Pseudo-implementation of class encapsulating interactions with MySQL. class UserMysqlDataGateway { use Marshaller; /** * Assumption that code calling this method extracted User data from entity * instance and passed in this $userData argument. */ public function put(\stdClass $userData) { // Default behaviour is to get all non-static properties and build // a map in such way that result of marshalling would contain all data // untouched (passed through) but keys would be underscore separated // instead of camelCase. $schema = SchemaBuilder::fromClassProperties(User::class)->build(); $record = $this->marshal($userData, $schema); $this->mysql->insert($record); } public function findById($id) { $record = $this->mysql->fetch('users', $id); $schema = SchemaBuilder::fromClassProperties(User::class)->build(); return $this->unmarshal($record, $schema); } }