multidots / zf3-rest-api
用于构建REST API的Zend Framework 3模块
Requires
- firebase/php-jwt: ^4.0
- zendframework/zend-json: ^3.0
This package is not auto-updated.
Last update: 2020-05-14 13:11:53 UTC
README
要求
此模块有以下要求
- Zend Framework 3或更高版本。
- PHP 7或更高版本。
安装
您可以使用composer将此模块安装到您的Zend Framework应用程序中。
安装composer包的推荐方法是
composer require multidots/zf3-rest-api
现在复制此文件 "vender/multidots/zf3-rest-api/config/restapi.global.php" 并粘贴到根目录 "config/autoload/restapi.global.php"
如果在包安装时未设置,请将此 'RestApi' 添加到 modules.config.php 文件中。
return [ .... //add this if not available 'RestApi' ];
使用
您只需创建一个与API相关的控制器,并将其扩展到 ApiController
而不是默认的 AbstractActionController
。您只需在 apiResponse
变量中设置您的结果,并在 httpStatusCode
变量中设置您的响应代码,然后返回 $this->createResponse()。例如,
namespace Application\Controller; use RestApi\Controller\ApiController; /** * Foo Controller */ class FooController extends ApiController { /** * bar method * */ public function barAction() { // your action logic // Set the HTTP status code. By default, it is set to 200 $this->httpStatusCode = 200; // Set the response $this->apiResponse['you_response'] = 'your response data'; return $this->createResponse(); } }
您可以在您的操作函数中定义您的逻辑,以满足您的需求。对于上面的例子,您将得到以下格式的响应 json
,
{"status":"OK","result":{"you_response":"your response data"}}
上述示例的URL将是 http://yourdomain.com/foo/bar
。您可以通过设置模块.config.php来自定义它,如下所示。
'router' => [ 'routes' => [ 'home' => [ 'type' => Literal::class, 'options' => [ 'route' => '/', 'defaults' => [ 'controller' => Controller\FooController::class, 'action' => 'bar', 'isAuthorizationRequired' => true // set true if this api Required JWT Authorization. ], ], ], ], ],
很简单 :)
配置
此模块提供与响应、请求和 JWT
认证相关的配置。默认配置在之前复制的 restapi.global.php 文件中。
<?php return [ 'ApiRequest' => [ 'responseFormat' => [ 'statusKey' => 'status', 'statusOkText' => 'OK', 'statusNokText' => 'NOK', 'resultKey' => 'result', 'messageKey' => 'message', 'defaultMessageText' => 'Empty response!', 'errorKey' => 'error', 'defaultErrorText' => 'Unknown request!', 'authenticationRequireText' => 'Authentication Required.', 'pageNotFoundKey' => 'Request Not Found.', ], 'jwtAuth' => [ 'cypherKey' => 'R1a#2%dY2fX@3g8r5&s4Kf6*sd(5dHs!5gD4s', 'tokenAlgorithm' => 'HS256' ], ] ];
使用JWT进行请求认证
您可以在API请求中检查auth token的存在。您需要将标志 isAuthorizationRequired
设置为 true
或 false
。例如,
'router' => [ 'routes' => [ 'home' => [ 'type' => Literal::class, 'options' => [ 'route' => '/', 'defaults' => [ 'controller' => Controller\FooController::class, 'action' => 'bar', 'isAuthorizationRequired' => true // set true if this api Required JWT Authorization. ], ], ], ], ],
上述API方法将需要在请求中提供auth token。您可以在header、GET参数或POST字段中传递auth token。
如果您想通过header传递token,请使用以下格式。
Authorization: Bearer [token] Example: Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidmFsdWUifQ.xQgVrW5o3iNzA4iY3NDKwDp-pYoIhr-vyFgmi9RuMFo
在GET或POST参数的情况下,请在 token
参数中传递token。
生成jwt token
此模块提供生成jwt token并使用相同密钥和算法进行签名的方法。在需要时使用 $this->generate()
方法。您最有可能需要在用户登录和注册API中使用它。以下是一个示例,
public function login() { /** * process your data and validate it against database table */ // generate token if valid user $payload = ['email' => $user->email, 'name' => $user->name]; $this->apiResponse['token'] = $this->generateJwtToken($payload); $this->apiResponse['message'] = 'Logged in successfully.'; return $this->createResponse(); }
响应格式
API的响应格式是 json
,其结构如下。
{ "status": "OK", "result": { //your result data } }
示例
以下示例可帮助您了解此模块的工作原理。
检索文章
让我们创建一个API,它返回一系列包含基本详情(如id和标题)的文章。我们的控制器看起来像这样,
<?php namespace Application\Controller; use RestApi\Controller\ApiController; /** * Articles Controller * * */ class ArticlesController extends ApiController { /** * index method * */ public function indexAction() { // $this->token gives you to token which generated. // $this->tokenPayload gives you to payload details which you sets at the time of login or generate token. $payload = $this->tokenPayload; $articles = $this->entityManager->getRepository(Article::class) ->findBy([], ['id'=>'ASC']); $this->apiResponse['articles'] = $articles; return $this->createResponse(); } }
上述API调用的响应将如下所示,
{ "status": "OK", "result": { "articles": [ { "id": 1, "title": "Lorem ipsum" }, { "id": 2, "title": "Donec hendrerit" } ] } }
问题报告
如果您在此模块或任何错误中发现问题,请于GitHub上创建一个issue。