xeolope / cartographer
一个将JSON文档映射到对象的超级简单库,类似于Java的Jackson
v0.6.1
2015-01-28 20:49 UTC
Requires
- php: >=5.4
- minime/annotations: ~2.0
Requires (Dev)
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-09-07 14:51:51 UTC
README
Cartographer是一个将JSON反序列化为POPO的超级简单库,类似于FasterXML的jackson-databind
包。
安装
可以使用Composer安装此库,只需在您的composer.json
中包含以下内容
{ "require": { "xenolope/cartographer": "~0.5" } }
使用方法
POPOs
您的POPOs必须有一个属性和相应的setter,属性必须有一个@var ClassName
文档块,或者setter必须有一个类型提示。
setter将被直接调用,属性永远不会被触及,即使它们被声明为public
(尽管这可能会在以后的版本中添加)。
简单值被转换为它们@var
文档块中给出的类型(使用settype()
),对象根据@var
文档块中指定的类创建,对象数组也被创建,可以使用@var ClassName[]
表示法指定。
class Contact { /** * @var string */ private $name; /** * @var Address */ private $address; /** * Note, this property doesn't have a @var docblock, but the corresponding setter * below *does* have a type hint */ private $secondaryAddress; /** * @var Note[] */ private $notes; /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @param Address $address */ public function setAddress($address) { $this->address = $address; } /** * @param Address $secondaryAddress */ public function setAddress(Address $secondaryAddress) { $this->secondaryAddress = $secondaryAddress; } /** * @param Note[] $notes */ public function setNotes($notes) { $this->notes = $notes; } }
映射
// Create a new instance of the Mapper $mapper = new \Xenolope\Cartographer\Mapper(); // Map a JSON string to a POPO // PHP 5.4 $object = $mapper->mapString( '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}', 'Vendor\Package\Entity\Contact' ); // PHP >=5.5 $object = $mapper->mapString( '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}', Contact::class ); // Map an already decoded (to array) JSON document to a POPO // This might happen automatically in your Request class, for example $jsonDocument = json_decode( '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}', true ); // PHP 5.4 $object = $mapper->map($jsonDocument, 'Vendor\Package\Entity\Contact'); // PHP >= 5.5 $object = $mapper->map( '{"name":"Liz Lemon","address":{"street":"168 Riverside Dr.","city":"New York"}}', Contact::class );
路线图
- 添加自定义属性映射,当JSON属性与POPO属性不匹配时
- 可能添加将POPO序列化为JSON的支持
感谢
此库受到了以下启发
fasterxml/jackson-databind
for Javanetresearch/jsonmapper
for PHP
许可证
Cartographer在MIT许可证下发布;有关更多信息,请参阅LICENSE。