1. Go to this page and download the library: Download tobscure/json-api library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tobscure / json-api example snippets
use Tobscure\JsonApi\Document;
use Tobscure\JsonApi\Collection;
// Create a new collection of posts, and specify relationships to be h that collection as the data.
$document = new Document($collection);
// Add metadata and links.
$document->addMeta('total', count($posts));
$document->addLink('self', 'http://example.com/api/posts');
// Output the document as JSON.
echo json_encode($document);
use Tobscure\JsonApi\AbstractSerializer;
class PostSerializer extends AbstractSerializer
{
protected $type = 'posts';
public function getAttributes($post, array $fields = null)
{
return [
'title' => $post->title,
'body' => $post->body,
'date' => $post->date
];
}
}
public function getId($post)
{
return $post->someOtherKey;
}
public function comments($post)
{
$element = new Collection($post->comments, new CommentSerializer);
return new Relationship($element);
}
public function getRelationship($model, $name)
{
// resolve Relationship called $name for $model
}
$document = new Document;
$document->addMeta('key', 'value');
$document->setMeta(['key' => 'value']);
$resource = new Resource($data, $serializer);
$resource->addLink('self', 'url');
$resource->setLinks(['key' => 'value']);
$document->addPaginationLinks(
'url', // The base URL for the links
[], // The query params provided in the request
40, // The current offset
20, // The current limit
100 // The total number of results
);
use Tobscure\JsonApi\AbstractSerializer;
class PostSerializer extends AbstractSerializer
{
// ...
public function getLinks($post) {
return ['self' => '/posts/' . $post->id];
}
public function getMeta($post) {
return ['some' => 'metadata for ' . $post->id];
}
}
use Tobscure\JsonApi\Parameters;
$parameters = new Parameters($_GET);
// GET /api?$parameters->getInclude(['author', 'comments', 'comments.author']); // ['author', 'comments']