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
Requires
- php: ^7.3
- dkx/json-api: ^2.0.1
- dkx/paginator: ^0.2.1
- dkx/wrapped-http-response: ^2.0.0
- nette/utils: ^3.0
- psr/http-message: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- phpstan/extension-installer: ^1.0
- phpstan/phpstan: ^0.11.8
- phpstan/phpstan-strict-rules: ^0.11.1
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);