** 注意: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 app\controller;
use OpenApi\Attributes as OA;
#[OA\Info(
title: "THINKPHP8 API文档",
version: "1.0.1",
description: "THINKPHP8项目接口文档",
contact: new OA\Contact(
name: "THINKPHP8",
email: "support@xxx.com",
url: "https://xxx.com"
)
)]
#[OA\Tag(
name: "Index",
description: "首页相关接口"
)]
#[OA\Tag(
name: "Merchant",
description: "商户相关接口"
)]
class Swagger
{
}
4、 在需要扫描的控制器类(Merchant.php)中加入注解:
<?php
namespace app\controller;
use OpenApi\Attributes as OA;
class Merchant extends BaseApp
{
#[OA\Post(
path: "/api/merchant/register",
summary: "商户注册",
tags: ["Merchant"],
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ["email", "password", "timestamp", "sign"],
properties: [
new OA\Property(property: "email", type: "string", description: "邮箱"),
new OA\Property(property: "password", type: "string", description: "密码"),
new OA\Property(property: "timestamp", type: "integer", description: "时间戳"),
new OA\Property(property: "sign", type: "string", description: "签名"),
]
)
),
responses: [
new OA\Response(
response: 200,
description: "注册成功"
),
new OA\Response(
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/#/,即可看到接口文档。