R3VoLuT1OneR /
jsonapi-resource
| 1 | <?php |
||
| 2 | |||
| 3 | // Please change the path to your autoload |
||
| 4 | include __DIR__.'/../../vendor/autoload.php'; |
||
| 5 | include __DIR__.'/Articles.php'; |
||
| 6 | include __DIR__.'/People.php'; |
||
| 7 | |||
| 8 | use JSONAPI\Resource\Fieldset; |
||
| 9 | use JSONAPI\Resource\Includeset; |
||
| 10 | use JSONAPI\Resource\Serializer; |
||
| 11 | |||
| 12 | // Prepare our mock data, in real example it is fetched using ORM |
||
| 13 | $pavel = new People(17, 'Pavel Z', 31); |
||
| 14 | $dan = new People(18, 'Dan', 43); |
||
| 15 | $article1 = new Articles(1, 'PHP JSON:API Resource', $pavel); |
||
| 16 | $article2 = new Articles(2, 'How to create JSON:API', $dan); |
||
| 17 | |||
| 18 | // Collection of all available articles |
||
| 19 | $collection = [$article1, $article2]; |
||
| 20 | |||
| 21 | // fields[people]=age |
||
| 22 | $fieldset = new Fieldset(['people' => 'age']); |
||
| 23 | |||
| 24 | // include=author |
||
| 25 | $includeset = Includeset::fromString('author'); |
||
| 26 | |||
| 27 | $serializer = new Serializer( |
||
| 28 | fieldset: $fieldset, |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 29 | includeset: $includeset, |
||
| 30 | ); |
||
| 31 | |||
| 32 | // Our main data |
||
| 33 | $data = $serializer->serialize($collection); |
||
| 34 | |||
| 35 | // It is how we fetch compound data or included data |
||
| 36 | $included = $serializer->compoundData(); |
||
| 37 | |||
| 38 | echo json_encode(['data' => $data, 'included' => $included], JSON_PRETTY_PRINT); |
||
| 39 |