PHP code example of sarbinski / json-api

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

    

sarbinski / json-api example snippets



Data loaded from database(for example)
$data = [
    ['id' => '1', 'name' => 'Foo'],
    ['id' => '2', 'name' => 'Bar'],
];

$api = new Sarbinski\JsonApi\Api();
$api->createData($dataObject, 'Sarbinski\JsonApi\Schemas\TestSchema');
echo $api->buildMainJSONStructure()->getPrintData(true);


class TestSchema extends Schema
{
    protected $type = 'test-schema';

    public function getAttributes($resource)
    {
        return [
            'name' => $resource['id'] . '_' . $resource['name'],
        ];
    }

    public function getId($resource)
    {
        return $resource['id'];
    }

    public function getRelationships($resource)
    {
        return false;
    }
}


class DataClass implements Iterator {
    private $items = [];

    public function __construct()
    {
        $this->items = [
            ['id' => 1, 'name' => 'a'],
            ['id' => 2, 'name' => 'b'],
        ];
    }

    public function current()
    {
        return current($this->items);
    }

    public function key()
    {
        return key($this->items);
    }

    public function next()
    {
        return next($this->items);
    }

    public function rewind()
    {
        return reset($this->items);
    }

    public function valid()
    {
        return key($this->items) !== null;
    }
}

$dataObject = new DataClass();
$api->createData($dataObject, 'Sarbinski\JsonApi\Schemas\TestSchema');
echo $api->buildMainJSONStructure()->getPrintData(true);