packeto / rest-router
Nette 框架的 REST 路由扩展,具有简单的注解功能。
v1.0.9
2018-09-02 04:09 UTC
Requires
- php: >= 7.1.0
- doctrine/annotations: ~1.6
- doctrine/cache: ^1.7.1
- league/json-guard: ^1.0
- nette/application: ^2.3
- nette/di: ^2.3
- nette/http: ^2.3
- nette/reflection: ^2.3
- nette/utils: ^2.3
README
基本的 REST API 路由扩展,带有注解辅助工具。
安装
通过 Composer 安装依赖
composer require packeto/rest-router
在配置文件中注册扩展
extensions: apirouter: Packeto\RestRouter\DI\RestRouterExtension
配置 JSON 模式目录
apirouter: jsonSchemasPath: %appDir%/../json-schema
使用
ResourcePresenter
路由在扩展自扩展提供的 ResourcePresenter
的 Presenter 中定义
/** * @ApiRoute( * "/api/v1/hello", * presenter="Api:Hello" * ) */ class HelloPresenter extends ResourcePresenter { /** * @Authenticated * @JsonSchema("users/hello.json") * @DTO("API\Commands\DTO\HelloDTO") */ public function actionCreate() { // Instance of API\Commands\DTO\HelloDTO $dto = $this->getCommandDTO(); $this->sendSuccessResponse(); } }
JSON 模式验证
请求(POST
、PUT
、PATCH
)可以使用 JSON 模式 进行验证。您必须在您的配置中配置 jsonSchemasPath
。
然后在此文件夹中创建 JSON 模式文件,例如 test.json
,并在方法注解中放置此文件名
@JsonSchema("test.json")
然后执行之前,将对输入进行验证。很简单。
请求认证
扩展为您提供了 @Authenticated
注解,该注解可对指向端点的每个请求进行认证。您必须通过实现 IAuthenticator
来实现自己的逻辑。
实现示例
use Nette\Http\IRequest; use Packeto\RestRouter\Exception\Api\AuthenticationException; use Packeto\RestRouter\Security\IAuthenticator; class Authenticator implements IAuthenticator { private const AUTHENTICATION_HEADER = 'X-Api-Key'; /** * @param IRequest $request * @return void * @throws AuthenticationException */ public function authenticate(IRequest $request): void { if (is_null($request->getHeader(self::AUTHENTICATION_HEADER, null))) { throw new AuthenticationException( sprintf('Header %s is empty, or is not provided.', self::AUTHENTICATION_HEADER), AuthenticationException::MISSING_HEADER_VALUE ); } return; } }
然后将在您的配置中将您的 API 认证器注册为服务。