scorpjio / zf3-rest-api
用于构建REST API的Zend Framework 3模块
Requires
- firebase/php-jwt: ^4.0
- zendframework/zend-json: ^3.0
This package is auto-updated.
Last update: 2024-09-11 00:05:19 UTC
README
###(这是一个来自https://github.com/multidots的已删除仓库)
需求
此模块有以下需求
- Zend Framework 3或更高版本。
- PHP 7或更高版本。
安装
您可以使用 composer 将此模块安装到您的Zend Framework应用程序中。
安装composer包的推荐方式是
composer require scorpjio/zf3-rest-api
现在将此文件 "vendor/scorpjio/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(); } }
您可以在您的操作函数中定义您的逻辑,具体取决于您的需求。对于上述示例,您将获得以下响应格式的响应,
{"status":"OK","result":{"you_response":"your response data"}}
上述示例的URL将是 http://yourdomain.com/foo/bar
。您可以通过以下方式自定义它。
'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,它返回具有基本详情如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 上提交问题。