我正在构建 Zend Expressive 2 REST API (JSON) 并希望直接对我的 API 进行版本控制。我使用 Zend ServiceManager + FastRoute 进行路由。
我找到了 REST API 版本控制的有用链接,并决定在请求标头中使用版本控制:
- https://apigility.org/documentation/api-primer/versioning
- https://stackoverflow.com/questions/389169/best-practices-for-api-versioning
问题:
如何实现 api 版本控制;详细路由到中间件操作;在zend express 2中?(使用快速路由)
接受标头(带有版本的 JSON API):
Accept: application/vnd.api+json;version=2
所需结构(应用):
/
config/
data/
public/
src/
App/
V1/
Action/
SomeResource.php // <- in Version 1
...
V2/
Action/
SomeResource.php // <- in Version 2
...
...
vendor/
...
我的代码片段:(版本检测有效,但如何路由?)
管道.php
<?php
// ...
// The error handler should be the first (most outer) middleware to catch
// all Exceptions.
$app->pipe(ErrorHandler::class);
$app->pipe(ContentTypeJsonApiVersioning::class); // <-- detect version work quite well
$app->pipe(ServerUrlMiddleware::class);
路由.php
<?php
// ...
//
$app->route('/api/some-resource[/{id:\d+}]',
[
Auth\Action\AuthAction::class,
Zend\Expressive\Helper\BodyParams\BodyParamsMiddleware::class,
App\Action\SomeResourceAction::class
],
['GET', 'POST', 'PUT', 'DELETE'],
'api.route.name'
);
ContentTypeJsonApiVersioning.php
<?php
namespace App\Middleware;
use Fig\Http\Message\StatusCodeInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Middleware to detect accept is JSON API (application/vnd.api+json) and separate version
*/
class ContentTypeJsonApiVersioning
{
/**
* @const string
*/
const EXPECTED_TYPE_JSON_API = 'application/vnd.api+json';
/**
* Execute the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @throws \InvalidArgumentException
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
// error: return response with code: 415
$return = $response->withStatus(StatusCodeInterface::STATUS_UNSUPPORTED_MEDIA_TYPE);
$acceptHeader = $request->getHeader('Accept');
if (isset($acceptHeader[0])) {
$data = $this->_processAcceptHeader($acceptHeader[0]);
if (self::EXPECTED_TYPE_JSON_API === $data['accept']) {
// continue processing
$return = $next($request->withAttribute('version', $data['version']), $response);
}
}
return $return;
}
/**
* @param string $acceptHeader
* @return array
*/
protected function _processAcceptHeader(string $acceptHeader) : array
{
// expected: "application/vnd.api+json; version=2.1"
$data = \explode(';', $acceptHeader);
$return = [
'accept' => $data[0],
'version' => '1'
];
// on 2 items, 2nd is version parameter
if (2 === \count($data)) {
// split: "version=2.1" to "2.1"
list(,$return['version']) = \explode('=', \trim($data[1]));
}
return $return;
}
}