abirchler / laminas-rest-api
Laminas模块,用于构建REST API
Requires
- firebase/php-jwt: ^6.0
- laminas/laminas-json: ^3.0
README
###(这是一个来自 https://github.com/multidots 的已删除仓库)
要求
此模块有以下要求
- Laminas框架。
- PHP 7或更高版本。
安装
您可以使用 composer 将此模块安装到您的Laminas框架应用程序中。
安装composer包的推荐方法是
composer require abirchler/laminas-rest-api
现在将此文件 "vendor/abirchler/laminas-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令牌。您需要将标志 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令牌。您可以通过头、GET参数或POST字段传递auth令牌。
如果您想在头中传递令牌,请使用以下格式。
Authorization: Bearer [token] Example: Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidmFsdWUifQ.xQgVrW5o3iNzA4iY3NDKwDp-pYoIhr-vyFgmi9RuMFo
在GET或POST参数的情况下,请将令牌传递到 token
参数。
生成jwt令牌
此模块提供了生成jwt令牌并使用相同密钥和算法进行签名的方法。在需要时使用 $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,该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 上打开问题。