neomerx / json-api

Framework agnostic JSON API (jsonapi.org) implementation

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to encode custom array NOT LARAVEL MODEL INSTANCE

beselmonster opened this issue · comments

image
I just want to use my custom schema DropLineSchema to encode custom array which is array of arrays.
How to do that? Is every array in array required to be laravel model? I cant really figure out. All examples i saw had laravel models in it

Hi, the library is framework agnostic and knows nothing about Laravel or any other framework.

Though it has some requirements for inputs. Simply put, you should pass either a class instance or an array of instances. The classes could be anything from \stdClass to Custom or Laravel or Doctrine models. The Schemas are the classes that know how to extract needed data from those 'models'.

For you it could be

class DropLine
{
    public int $id;
    public int $length;
    public int $indent;
    public string $value;
}

$arrayOfDropLines = ...;

$json = Encoder::instance([
    DropLine::class => DropLineSchema::class,
])->encodeData($arrayOfDropLines);

Thanks. But is there any option i can use array of arrays? When i try it, i have an error
"assert(): assert($dataOrId instanceof SchemaIdentifierInterface) failed".

@beselmonster I know nobody likes reading manuals 😄 but the spec probably do not have such thing as array of arrays therefore this lib do not have it. Array of objects might be helpful for you as shown in the example above.