2

我正在构建 Zend Expressive 2 REST API (JSON) 并希望直接对我的 API 进行版本控制。我使用 Zend ServiceManager + FastRoute 进行路由。

我找到了 REST API 版本控制的有用链接,并决定在请求标头中使用版本控制:

问题:

如何实现 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;
    }

}
4

1 回答 1

0

fastroute 所做的是在 URL 上抛出一个正则表达式并解析它。所以传递请求属性是行不通的。我可以想出几种方法来使它工作:

  • 不要在标头中使用版本控制,而是在 url 中使用它。但既然你是专门要求的,我想这不是一个选择。
  • 重写 ContentTypeJsonApiVersioning 中的 URL 并在请求传递到路由器之前对其进行更新。所以基本上重写为/api/v1/resource/id
  • 将所有 api 请求传递给 APiMiddlewareAction 并在其中检查请求中传递的版本并加载正确的操作。

在最后一种情况下,您可能只有一条类似于以下的路线:

[
    'name'            => 'api',
    'path'            => '/api/{resource:\w+}[/{resourceId:\d+}[/{relation:\w+}[/{relationId:\d+}]]]',
    'middleware'      => ApiMiddleware::class,
    'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
    'options'         => [
        'defaults' => [
        ],
    ],
],

可能还有更多的解决方案。

于 2017-10-22T05:53:11.097 回答