PHPackages                             mvieira/collection-json - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. mvieira/collection-json

ActiveLibrary[HTTP &amp; Networking](/categories/http)

mvieira/collection-json
=======================

PHP implementation of the Collection+JSON Media Type

v2.1.0(8y ago)1691[4 issues](https://github.com/mickaelvieira/CollectionJson/issues)MITPHPPHP &gt;=7.0

Since Apr 28Pushed 8y ago2 watchersCompare

[ Source](https://github.com/mickaelvieira/CollectionJson)[ Packagist](https://packagist.org/packages/mvieira/collection-json)[ Docs](https://github.com/mickaelvieira/CollectionJson)[ RSS](/packages/mvieira-collection-json/feed)WikiDiscussions master Synced today

READMEChangelog (4)Dependencies (6)Versions (8)Used By (0)

Collection Json
===============

[](#collection-json)

[![Software License](https://camo.githubusercontent.com/850eae1099d2b05f53383473d7cd51f9bc1ab09b7d0d9e5122f1dd930efdcc6d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6d6173686170652f6170697374617475732e737667)](https://github.com/mickaelvieira/CollectionJson/blob/master/LICENSE.md)[![Latest Stable Version](https://camo.githubusercontent.com/094fb7235ee1bbd73301978d0bcc94fe5fc916192e2ca6f393da65adac94408b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d7669656972612f636f6c6c656374696f6e2d6a736f6e2e737667)](https://packagist.org/packages/mvieira/collection-json)[![Build Status](https://camo.githubusercontent.com/09dabf265f3ab88af89b2def8d0099b981d7ca8145950b613109f3517245f692/68747470733a2f2f7472617669732d63692e6f72672f6d69636b61656c7669656972612f436f6c6c656374696f6e4a736f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/mickaelvieira/CollectionJson)[![Coverage Status](https://camo.githubusercontent.com/57c2c3d63b5648fdbff2ca2773c1d971433ee80ac2724004b1a2669130cd1b97/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6d69636b61656c7669656972612f436f6c6c656374696f6e4a736f6e2f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/mickaelvieira/CollectionJson?branch=master)

PHP implementation of the Collection+JSON Media Type

Specification:

-

Installation
------------

[](#installation)

CollectionJson requires php &gt;= 7.0

Install CollectionJson with [Composer](https://getcomposer.org/)

```
{
    "require": {
        "mvieira/collection-json": "dev-master"
    }
}
```

or

```
$ composer require mvieira/collection-json
```

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](https://github.com/mickaelvieira/CollectionJson/tree/master/CONTRIBUTING.md) for details.

License
-------

[](#license)

The MIT License (MIT). Please see [License File](https://github.com/mickaelvieira/CollectionJson/tree/master/LICENSE.md) for more information.

Documentation
-------------

[](#documentation)

### Creating a collection

[](#creating-a-collection)

```
$collection = (new Collection())
    ->withItem((new Item('https://example.co/item/1'))
        ->withDataSet([
            new Data('data 1'),
            new Data('data 2', 'value 2')
        ])
        ->withLink(
            new Link('https://example.co/item/1', Relation::ITEM)
        )
    );

print json_encode($collection);
```

```
{
    "collection": {
        "version": "1.0",
        "items": [
            {
                "data": [
                    {
                        "name": "data 1",
                        "value": null
                    },
                    {
                        "name": "data 2",
                        "value": "value 2"
                    }
                ],
                "href": "http:\/\/example.com\/item\/1",
                "links": [
                    {
                        "href": "https:\/\/example.co\/item\/1",
                        "rel": "item",
                        "render": "link"
                    }
                ]
            }
        ]
    }
}
```

### Creating an entity

[](#creating-an-entity)

All entities `Collection`, `Data`, `Error`, `Item`, `Link`, `Query`, `Template` can be created by using the static method `fromArray`...

```
$data = Data::fromArray([
    'name' => 'email',
    'value' => 'hello@example.co'
]);
```

...or by using the accessors (Note that entities are immutable)

```
$data = (new Data('email'))
    ->withValue('hello@example.co');
```

...or via the constructor

```
$data = new Data('email', 'hello@example.co');
```

### Printing the data

[](#printing-the-data)

Note: Apart from the data's value property, which allows having a NULL value (see. [specification](http://amundsen.com/media-types/collection/format/#properties-value)), All `NULL` properties and empty arrays will be excluded from the JSON and Array representation.

#### Printing a JSON representation

[](#printing-a-json-representation)

All entities implement the [JsonSerializable](http://php.net/manual/en/class.jsonserializable.php) interface, you can therefore call at any time the method `json_encode()`.

```
print json_encode($collection);
```

```
{
    "collection": {
        "version": "1.0",
        "items": [
            ...
        ],
        "links": [
            ...
        ]
    }
}
```

#### Printing an Array representation

[](#printing-an-array-representation)

All entities implement a custom interface named `ArrayConvertible`, so you can call at any time the method `toArray()`. This method will be called recursively on all nested entities.

```
print_r($collection->toArray());
```

```
Array
(
    [collection] => Array
        (
            [version] => 1.0
            [items] => Array
                ...

            [links] => Array
                ...

        )

)
```

#### Wrapping

[](#wrapping)

The `CollectionJson\Entity\Collection` entity will be wrapped...

```
echo json_encode($collection);
```

```
{
    "collection": {
        "version": "1.0"
     }
}
```

...however others entities will not be wrapped when they are converted in a JSON or an Array.

```
$template = new Template();
echo json_encode($template);
```

```
{
    "data": [
        ...
    ]
}
```

But you can wrap the json or the array representation by calling the method `wrap()`

```
$template->wrap();
echo json_encode($template);
```

```
{
    "template": {
        "data": [
            ...
        ]
    }
}
```

### Examples

[](#examples)

Examples are available in the directory `./examples/`, you can execute them on the command line by running:

```
$ make examples
```

Or separately

```
$ php ./examples/client-collection.php

```

### Working with data and links

[](#working-with-data-and-links)

In order to work with CollectionJson Arrays [Data](http://amundsen.com/media-types/collection/format/#arrays-data), [Links](http://amundsen.com/media-types/collection/format/#arrays-links), the API provides 2 interfaces that implement a similar logic.

- The interface `DataAware` implemented by `Item`, `Query` and `Template` entities, provides the methods `withData`, `withoutData`, `withDataSet`, `getDataSet`, `getFirstData` and `getLastData`
- The interface `LinkAware` implemented by `Collection` and `Item` entities, provides the methods `withLink`, `withoutLink`, `withLinkSet`, `getLinks`, `getFirstLink` and `getLastLink`

They allows you to add the corresponding entities to objects that implement them.

```
// this...
$item = (new Item('https://example.co/item/1'))
    ->withData([
        'name' => 'email',
        'value' => 'email value'
    ]);

// ...is similar to
$data = Data::fromArray([
    'name' => 'email',
    'value' => 'email value'
]);

$item = (new Item('https://example.co/item/1'))
    ->withData($data);

// and that...
$item = (new Item('https://example.co/item/1'))
    ->withDataSet([
        new Data('email', 'hello@example.co'),
        new Data('tel', '0000000000')
    ]);

// ...is similar to
$data1 = Data::fromArray([
    'name' => 'email',
    'value' => 'hello@example.co'
]);
$data2 = Data::fromArray([
    'name' => 'tel',
    'value' => '0000000000'
]);
$item = (new Item('https://example.co/item/1'))
    ->withDataSet([
        $data1,
        $data2
    ]);
```

### Validation

[](#validation)

It is now possible to validate the data entering your API by using the [Symfony validator](https://symfony.com/doc/current/components/validator.html).

```
use CollectionJson\Validator\Dataset as DatasetValidator;
use Symfony\Component\Validator\Constraints;

$constraints = [
    'id' => [
        new Constraints\NotBlank(),
    ],
    'url' => [
        new Constraints\NotBlank(),
        new Constraints\Url(),
    ],
    'email' => [
        new Constraints\NotBlank(),
        new Constraints\Email(),
    ],
];

$template = (new Template())
    ->withData(new Data('id', '123'))
    ->withData(new Data('url', 'http://example.co'))
    ->withData(new Data('email', 'test@example.co'));

$errors = (new DatasetValidator())
    ->validate($template->getDataSet(), $constraints);
```

It will return the list of errors.

###  Health Score

24

—

LowBetter than 31% of packages

Maintenance0

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~89 days

Recently: every ~130 days

Total

7

Last Release

3178d ago

Major Versions

1.2.0.x-dev → 2.0.02017-07-22

PHP version history (2 changes)1.0.0PHP &gt;=5.5

2.0.0PHP &gt;=7.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/54a9031d93c5538389f6f505716a19f552d2b40e2bbfa330ddbca95c6e6fa573?d=identicon)[mickaelvieira](/maintainers/mickaelvieira)

---

Top Contributors

[![mickaelvieira](https://avatars.githubusercontent.com/u/3251585?v=4)](https://github.com/mickaelvieira "mickaelvieira (262 commits)")

---

Tags

httpjsonrestrestfulhypermediaHATEOAS

###  Code Quality

Code StylePHP\_CodeSniffer

### Embed Badge

![Health badge](/badges/mvieira-collection-json/health.svg)

```
[![Health](https://phpackages.com/badges/mvieira-collection-json/health.svg)](https://phpackages.com/packages/mvieira-collection-json)
```

###  Alternatives

[nategood/httpful

A Readable, Chainable, REST friendly, PHP HTTP Client

1.8k17.5M274](/packages/nategood-httpful)[nocarrier/hal

application/hal builder / formatter for PHP 5.3+

2002.0M21](/packages/nocarrier-hal)[jacwright/restserver

php rest server for very light-weight REST APIs

50871.6k3](/packages/jacwright-restserver)[ismaeltoe/osms

PHP library wrapper of the Orange SMS API.

4540.5k](/packages/ismaeltoe-osms)[jsor/hal-client

A lightweight client for consuming and manipulating Hypertext Application Language (HAL) resources.

2226.0k1](/packages/jsor-hal-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
