jjware / phpcollectionjson
用于构建 Collection+JSON 响应的 PHP 类
3.2.0
2016-10-11 13:33 UTC
Requires
- php: >=5.5.0
This package is not auto-updated.
Last update: 2024-09-14 19:53:09 UTC
README
用于构建 Collection+JSON 响应的 PHP 类。
安装
composer require jjware/phpcollectionjson
使用
创建响应
use PhpCollectionJson\Document; use PhpCollectionJson\Collection; use PhpCollectionJson\Item; use PhpCollectionJson\Data; $document = new Document(); $collection = new Collection('http://www.somesite.com/users'); $document->setCollection($collection); $item = new Item('http://www.somesite.com/users/123'); $item->getData() ->add(new Data('firstName', 'John')) ->add(new Data('lastName', 'Smith')) ->add(new Data('username', 'jsmith')); $collection->getItems()->add($item); echo json_encode($document);
从响应构建
JSON
{
"collection": {
"version": "1.0",
"href": "http://www.somesite.com/users",
"items": [
{
"href": "http://www.somesite.com/users/123",
"data": [
{
"name": "firstName",
"value": "John"
},
{
"name": "lastName",
"value": "Smith"
},
{
"name": "username",
"value": "jsmith"
}
]
}
]
}
}
PHP
use PhpCollectionJson\Document; $json = file_get_contents('http://www.somesite.com/users'); // don't do this at home kids $document = Document::fromJSON($json); $firstName = $document->getCollection()->getItems()->elementAt(0)->getData()->elementAt(0)->getValue(); // $firstName === 'John'