注意:swagger-php 5.x 默认只支持 PHP 属性注解,不再推荐/默认支持 PHPDoc 注释!
1、 使用composer安装swagger-php
`composer require zircote/swagger-php`
2、 验证安装:
`./vendor/bin/openapi --version`
3、 在控制器目录controller下新建类Swagger.php:
`<?php
namespace appcontroller;
use OpenApiAttributes as OA;
#[OAInfo(
title: "THINKPHP8 API文档",
version: "1.0.1",
description: "THINKPHP8项目接口文档",
contact: new OAContact(
name: "THINKPHP8",
email: "[email protected]",
url: "https://xxx.com"
)
)]
#[OATag(
name: "Index",
description: "首页相关接口"
)]
#[OATag(
name: "Merchant",
description: "商户相关接口"
)]
class Swagger
{
}`

4、 在需要扫描的控制器类(Merchant.php)中加入注解:
`<?php
namespace appcontroller;
use OpenApiAttributes as OA;
class Merchant extends BaseApp
{
#[OAPost(
path: "/api/merchant/register",
summary: "商户注册",
tags: ["Merchant"],
requestBody: new OARequestBody(
required: true,
content: new OAJsonContent(
required: ["email", "password", "timestamp", "sign"],
properties: [
new OAProperty(property: "email", type: "string", description: "邮箱"),
new OAProperty(property: "password", type: "string", description: "密码"),
new OAProperty(property: "timestamp", type: "integer", description: "时间戳"),
new OAProperty(property: "sign", type: "string", description: "签名"),
]
)
),
responses: [
new OAResponse(
response: 200,
description: "注册成功"
),
new OAResponse(
response: 400,
description: "参数错误或签名失败"
)
]
)]
public function register()
{
}
}`

5、 运行扫描命令,自动扫描并生成public目录下的swagger.json文件:
`./vendor/bin/openapi --output ./public/swagger.json ./app/controller`
6、 下载swagger-ui,以便可以可视化呈现接口文档:
下载最新版本的swagger-ui文件,通常是dist.zip压缩包,解压后复制到项目public目录下,并修改swagger-initializer.js文件,将资源指向swagger.json
`window.ui = SwaggerUIBundle({
url: "/swagger.json",
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
});`

7、 运行或部署项目后,可访问127.0.0.1/swagger-ui/#/,即可看到接口文档。