PHP code example of neomerx / json-api

1. Go to this page and download the library: Download neomerx/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/ */

    

neomerx / json-api example snippets


$encoder = Encoder::instance([
        Author::class => AuthorSchema::class,
    ])
    ->withUrlPrefix('http://example.com/api/v1')
    ->withEncodeOptions(JSON_PRETTY_PRINT);

echo $encoder->encodeData($author) . PHP_EOL;

class AuthorSchema extends BaseSchema
{
    public function getType(): string
    {
        return 'people';
    }

    public function getId($author): ?string
    {
        return $author->authorId;
    }

    public function getAttributes($author, ContextInterface $context): iterable
    {
        return [
            'first-name' => $author->firstName,
            'last-name'  => $author->lastName,
        ];
    }

    public function getRelationships($author, ContextInterface $context): iterable
    {
        return [
            'comments' => [
                self::RELATIONSHIP_LINKS_SELF    => false,
                self::RELATIONSHIP_LINKS_RELATED => true,

                // Data