soBored / mezzio-rest-helpers
用于在 Mezzio 中构建 RESTful 处理器的辅助类
v1.0.1
2022-10-18 19:35 UTC
Requires
- php: ^7.3 || ~8.0.0 || ~8.1.0
- laminas/laminas-diactoros: ^2.14
- mezzio/mezzio: ^3.6
- mezzio/mezzio-hal: ^2.2
- mezzio/mezzio-problem-details: ^1.4
README
辅助类和路由,帮助在 Mezzio 中构建 RESTful 和 HAL 兼容的 API。
安装
使用 composer 安装此库
$ composer require sobored/mezzio-rest-helpers
RestDispatchTrait
使用此特质以简单方式创建 RESTful 响应
<?php declare(strict_types=1); namespace App\Handler; use Mezzio\Hal\HalResponseFactory; use Mezzio\Hal\ResourceGenerator; use App\Entity\UserEntity; use App\TableGateway\UserTableGateway; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use SoBoRed\Mezzio\Rest\Exception\NoResourceFoundException; use SoBoRed\Mezzio\Rest\RestDispatchTrait; class GetUserHandler implements RequestHandlerInterface { /** * @var UserTableGateway */ private $userTable; /** * Use REST Helper RestDispatchTrait to gain * $this->resourceGenerator, $this->responseFactory, * and $this->createResponse() */ use RestDispatchTrait; public function __construct( UserTableGateway $userTable, ResourceGenerator $resourceGenerator, HalResponseFactory $responseFactory ) { $this->userTable = $userTable; $this->resourceGenerator = $resourceGenerator; $this->responseFactory = $responseFactory; } public function handle(ServerRequestInterface $request) : ResponseInterface { $id = $request->getAttribute('id', false); $user = $this->userTable->get((int)$id)->current(); if (! $user instanceof UserEntity) { // Throw a REST Helper Exception for HAL-compliant problem details in response throw NoResourceFoundException::create("User with id `{$id}` not found"); } // Return a HAL-compliant response that contains the record requested return $this->createResponse($request, $user); } }
异常
SoBoRed/mezzio-rest-helpers 随带一些有用的异常,这些异常使用 mezzio/mezzio-problem-details 来生成易于阅读的 API 错误响应。上面使用的 NoResourceFoundException
的示例响应将是
{ "status": 404, "detail": "User with id `22` not found", "type": "/api/doc/resource-not-found", "title": "Resource not found" }
可用异常
- 状态 400: InvalidParameterException, OutOfBoundsException
- 状态 405: MethodNotAllowedException
- 状态 404: NoResourceFoundException
- 状态 500: RuntimeException
文档
为了使问题详情符合 HAL 标准,它们应该指向某种形式的文档,帮助用户理解他们遇到的问题。因此,mezzio-rest-helpers 提供了文档和路由,每个异常类型都指向它。
可用文档路由
- /api/doc/invalid-parameter
- /api/doc/method-not-allowed-error
- /api/doc/resource-not-found
- /api/doc/parameter-out-of-range
- /api/doc/runtime-error