PHP code example of hyperf-plus / swagger
1. Go to this page and download the library: Download hyperf-plus/swagger library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hyperf-plus / swagger example snippets
return [
'enable' => true,
'port' => 9501,
'json_dir' => BASE_PATH . '/runtime/swagger/',
'html' => '/swagger',
'url' => '/swagger/openapi.json',
'auto_generate' => true,
'scan' => [
'paths' => [BASE_PATH . '/app'],
],
];
use HPlus\Route\Annotation\ApiController;
use HPlus\Route\Annotation\GetApi;
use HPlus\Route\Annotation\PostApi;
use HPlus\Validate\Annotations\RequestValidation;
#[ApiController(tag: 'User Management')]
class UserController
{
#[GetApi(summary: '获取用户列表')]
#[RequestValidation(queryRules: [
'page' => 'integer|min:1',
'size' => 'integer|between:1,100',
])]
public function index() {}
#[PostApi(summary: '创建用户')]
#[RequestValidation(rules: [
'name' => '
use HPlus\Route\Annotation\ApiResponse;
#[GetApi]
#[ApiResponse(code: 200, description: '成功', schema: [
'id' => 'integer',
'name' => 'string',
])]
public function show($id) {}
use HPlus\Route\Annotation\ApiResponseExample;
#[GetApi]
#[ApiResponseExample(code: 200, example: [
'code' => 0,
'message' => 'success',
'data' => ['id' => 1, 'name' => 'John']
])]
public function show($id) {}
use HPlus\Route\Annotation\RequestBody;
#[PostApi]
#[RequestBody(
description: '用户信息',
create() {}
#[RequestValidation(rules: [
'name' => ''status' => 'in:active,inactive',
])]
return [
'enable' => env('SWAGGER_ENABLE', true),
'port' => 9501,
'json_dir' => BASE_PATH . '/runtime/swagger/',
'html' => '/swagger',
'url' => '/swagger/openapi.json',
'auto_generate' => true,
// OpenAPI 信息
'info' => [
'title' => 'My API',
'version' => '4.0.0',
'description' => 'API Documentation',
'contact' => [
'name' => 'API Support',
'email' => '[email protected] ',
],
],
// 服务器
'servers' => [
['url' => 'http://localhost:9501', 'description' => 'Development'],
['url' => 'https://api.example.com', 'description' => 'Production'],
],
// 安全方案
'security_schemes' => [
'bearerAuth' => [
'type' => 'http',
'scheme' => 'bearer',
'bearerFormat' => 'JWT',
],
],
// 扫描配置
'scan' => [
'paths' => [BASE_PATH . '/app/Controller'],
'ignore' => [BASE_PATH . '/app/Controller/AbstractController.php'],
],
];
// 注入 SwaggerBuilder
#[Inject]
private SwaggerBuilder $swaggerBuilder;
// 清除缓存后重新构建
$this->swaggerBuilder->clearCache();
$newDoc = $this->swaggerBuilder->build();
bash
php bin/hyperf.php vendor:publish hyperf-plus/swagger
bash
# 生成文档
php bin/hyperf.php swagger:generate
# 清除缓存
php bin/hyperf.php swagger:clear
# 验证文档
php bin/hyperf.php swagger:validate
# 导出文档
php bin/hyperf.php swagger:export --format=yaml
tests/
├── Cases/
│ ├── AbstractTestCase.php # 测试基类
│ └── SwaggerBuilderTest.php # 构建器测试
└── bootstrap.php