-
Notifications
You must be signed in to change notification settings - Fork 66
Home
Via Composer
$ composer require neomerx/json-api
In order to encode an arbitrary resource object to JSON API format, there are 3 main steps
- Create a
Schema
for the resource and resources it references. - Create an
Encoder
instance. - Encode resource(s), links, meta information or error(s).
A Schema
is a class that implements SchemaInterface
(BaseSchema
can be extended as it has some reasonable defaults) and provides information on how an arbitrary resource object(s) (class, Model, etc) should be converted to JSON API format. It gives
- Information about resource attributes.
- Information about resource relationships to other resources.
- Resource id, JSON API type, and URL.
- Conversion settings (e.g. if
self
andrelated
URLs should be shown, if meta information should be shown, etc). - Relationships information and data that should be placed to included section.
- Relationship pagination links.
For more details please check out the Schemas section
Encoder
class has a static method instance
/**
* Create encoder instance.
*
* @param array $schemas Schema providers.
*
* @return EncoderInterface
*/
public static function instance(array $schemas): EncoderInterface
which accepts an array of mapping between resource types and resource schemas
$encoder = Encoder::instance([
// class names as strings
'\Author' => '\AuthorSchema',
// '::class' constant (PHP 5.5+) convenient for classes in namespaces
Comment::class => CommentSchema::class,
// Schema instances could be used as well
Post::class => $postSchema,
// callables are also supported
Site::class => function (FactoryInterface $factory) use (...) {
$schema = new SiteSchema($factory, ..., ..., ...);
return $schema;
}
]);
Typically Schema mapping is stored in an external configuration file.
Instead of Schema
class name the default implementation can also accept SchemaInterface
instance or callable
which will be invoked on schema creation.
With advanced usage Schemas
can be completely custom and, for example, be dynamic and stored in a database.
For more see Schemas section.
Encode provides a few self-explanatory JSON API methods
-
encodeData($data): string
link -
encodeIdentifiers($data): string
link -
encodeError(ErrorInterface $error): string
andencodeErrors(iterable $errors): string
link -
encodeMeta($meta): string
link
Additionally, there are a few EncoderInterface
methods that set encoding options and add top level links, meta, set prefix to URLs, and etc to resulting JSON API document.
$isSubUrl = false;
$hasMeta = false;
$links = [
Link::FIRST => new Link($isSubUrl,'http://example.com/sites?first', $hasMeta),
Link::LAST => new Link($isSubUrl,'http://example.com/sites?last', $hasMeta),
Link::PREV => new Link($isSubUrl,'http://example.com/sites?prev', $hasMeta),
Link::NEXT => new Link($isSubUrl,'http://example.com/sites?next', $hasMeta),
];
$result = $encoder
->withEncodeOptions(JSON_PRETTY_PRINT)
->withUrlPrefix('http://example.com')
->withLinks($links)
->withMeta($meta)
->withIncludedPaths([
'posts',
'posts.author',
'posts.comments',
])
->withFieldSets([
// Attributes and relationships that should be shown
'sites' => ['name', 'posts'],
'posts' => ['author'],
'people' => ['first_name'],
])
->encodeData($site);
Encode options
and depth
are parameters for json_encode. Options
has predefined values described in official PHP documentation.
$links
is an optional parameter that could be used to specify JSON API top-level links section.
$meta
is an optional parameter that could be used to specify JSON API top-level meta section. This parameter could be any type that json_encode can work with (e.g. string, array, etc).
For certain cases a response with only meta information should be sent back to clients. This method provides such ability.
Input parameter $meta
could be any type that json_encode can work with (e.g. string, array, etc).
Encoder supports encoding JSON API Error objects.
Usage example
$error = new Error(
'some-id',
new Link(false, 'about-link', false),
[new LinkWithAliases(false, 'http://example.com/errors/123', ['v' => 'version'], false)],
'some-status',
'some-code',
'some-title',
'some-detail',
['source' => 'data'],
true,
['some' => 'meta']
);
Encoder::instance()->encodeError($error);
Sample result
{
"errors":[{
"id" : "some-id",
"links" : {
"about" : "about-link",
"type" : [{ "href": "http://example.com/errors/123", "aliases": {"v": "version"} }]
},
"status" : "some-status",
"code" : "some-code",
"title" : "some-title",
"detail" : "some-detail",
"source" : {"source" : "data"},
"meta" : {"some" : "meta"}
}]
}