dkx/json-api-middleware

This package is abandoned and no longer maintained. No replacement package was suggested.

Json api middleware

3.2.1 2019-12-09 09:59 UTC

This package is auto-updated.

Last update: 2024-01-09 19:06:41 UTC


README

Middleware for json api.

Based on dkx/json-api.

Installation

$ composer require dkx/json-api-middleware

Usage

<?php

use DKX\JsonApi\Manager;
use DKX\JsonApiMiddleware\JsonApiMiddleware;

$manager = new Manager;
$middleware = new JsonApiMiddleware($manager, 'include');

Example controller (Slim):

<?php

use DKX\JsonApiMiddleware\ItemResponse;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;

class DetailBookController
{
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
    {
        $book = loadBookById($args['id']);
        return new ItemResponse($response, $book);
    }
}

Or simply use DKX\JsonApiMiddleware\CollectionResponse when you need to transform an array of items.

Pagination

It's easy to use the CollectionResponse for small amounts of data, but for larger sets, you should use pagination.

This library works with dkx/paginator.

<?php

use DKX\JsonApiMiddleware\PaginatedResponse;
use DKX\Paginator\PaginatedData;

$currentPage = 1;
$itemsPerPage = 20;
$paginator = $paginatorFactory->create($totalCount, $currentPage);

$totalCount = getAllBooksCount();
$books = loadAllBooksWithPaginator($paginator);

$data = new PaginatedData($paginator, $books);
$response = new PaginatedResponse($response, $data);