codegalaxy / api-version-control
A Hyperf package to manage api versions
v1.0.1
2022-10-09 04:08 UTC
Requires
- php: >=7.4
This package is not auto-updated.
Last update: 2025-03-23 18:12:23 UTC
README
A Hyperf package to manage api versions.
安装
composer require codegalaxy/api-version-control
配置
php bin/hyperf.php vendor:publish codegalaxy/api-version-control
修改 config/autoload/version_control.php
中配置:
<?php
declare(strict_types=1);
use Hyperf\HttpServer\Contract\RequestInterface;
return [
'enable' => (bool) env('VERSION_CONTROL_ENABLE', true),
'versionParser' => function (RequestInterface $request) : ?float {
$version = $request->input('version');
return $version ? (float) $version : null;
},
];
定义路由
编写一个控制器 app/controller/VcController.php
,如下所示:
<?php
declare(strict_types=1);
namespace App\Controller;
class VcController extends AbstractController
{
public function none()
{
return 'none';
}
public function v1()
{
return 'v1';
}
public function v2()
{
return 'v2';
}
public function v3()
{
return 'v3';
}
public function v11()
{
return 'v1.1';
}
}
定义路由 config/routes.php
:
<?php
declare(strict_types=1);
use App\Controller\VcController;
use CodeGalaxy\ApiVersionControl\Router as VcRouter;
use Hyperf\HttpServer\Router\Router;
// 整体定义
Router::get('/vc/test', VcController::class . '@none', [
'vc' => [
'<=1' => VcController::class . '@v1',
'<=1.1' => VcController::class . '@v11',
'<=2' => VcController::class . '@v2',
'>=3' => VcController::class . '@v3',
],
]);
// 分版本定义
// 默认版本
VcRouter::apiVersion(null, function () {
VcRouter::get('/vc/test', VcController::class . '@none');
VcRouter::get('/vc/another', VcController::class . '@another');
});
// 版本<=1
VcRouter::apiVersion('<=1', function () {
VcRouter::get('/vc/test', VcController::class . '@v1');
VcRouter::get('/vc/another', VcController::class . '@anotherV1');
});
// 版本<=3
VcRouter::apiVersion('<=3', function () {
VcRouter::get('/vc/test', VcController::class . '@v3');
VcRouter::get('/vc/another', VcController::class . '@anotherV3');
});
// 必须在所有路由定义完成之后调用
VcRouter::load();
测试
curl http://127.0.0.1:9501/vc/test
# 响应 none
curl http://127.0.0.1:9501/vc/test?version=1
# 响应 v1
curl http://127.0.0.1:9501/vc/test?version=3
# 响应 v3