ankitgs / restapi
构建REST API的Zend Framework 3模块
Requires
- firebase/php-jwt: ^4.0
- zendframework/zend-json: ^3.0
This package is not auto-updated.
Last update: 2022-02-01 13:07:07 UTC
README
要求
此插件有以下要求
- Zend Framework 3或更高版本。
- PHP 7或更高版本。
安装
您可以使用composer将此插件安装到您的Zend Framework应用程序中。
安装composer包的推荐方法是
composer require multidots/zf3-restapi
安装后,转到根路径并打开composer.json文件,添加以下内容。
"autoload": { "psr-4": { .... // add following line. "restapi\\": "vendor/restapi/src/" } },
现在执行以下命令
composer dump-autoload
现在将此文件 "vender/restapi/config/restapi.global.php" 复制并粘贴到根目录 "config/autoload/restapi.global.php"
现在将此 'restapi' 添加到 modules.config.php 文件中。
return [ .... //add this '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. ], ], ], ], ],
Above API method will require auth token in request. You can pass the auth token in either header, in GET parameter or in POST field.
If you want to pass token in header, use below format.
```php
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 // $this->tokenPayload you can access user details. $this->tokenPayload = ['email' => $user->email, 'name' => $user->name]; $this->generateToken(); // $this->token through you can get token. $this->apiResponse['token'] = $this->token; $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() { $articles = $this->entityManager->getRepository(Article::class) ->findBy([], ['id'=>'ASC']); $this->apiResponse['articles'] = $articles; } }
上面API调用的响应将如下所示,
{ "status": "OK", "result": { "articles": [ { "id": 1, "title": "Lorem ipsum" }, { "id": 2, "title": "Donec hendrerit" } ] } }
报告问题
如果您在此插件或任何错误中遇到问题,请请在GitHub上打开一个issue。