ThinkPHP8 配置 Swagger

121 阅读1分钟

网上找了一圈 ThinPHP 的 Swagger 文档配置发现都不是很完善,故重新整理一篇

先安装 zircote/swagger-php 依赖

composer require zircote/swagger-php

再安装 doctrine/annotations 声明文件

composer require doctrine/annotations

编写一个自定义 command 命令,使其可以自动生成 swagger.json 到 public 目录下

php think make:command Swagger

在 app/command/Swagger.php 文件下写入自定义方法

<?php

declare (strict_types=1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use OpenApi\Generator;

class Swagger extends Command
{
    protected function configure(): void
    {
        $this->setName('swagger')
            ->setDescription('生成Swagger API文档');
    }

    protected function execute(Input $input, Output $output): void
    {
        // 确保扫描路径正确
        $openapi = (new Generator())->generate([app_path() . 'controller']);
        // 生成swagger.json文件
        $openapi->saveAs(public_path() . 'swagger.json');
        $output->writeln('Swagger文档生成成功!');
    }
}

还需要在 app/config/console.php 中加入自定义的指令

<?php

// +----------------------------------------------------------------------
// | 控制台配置
// +----------------------------------------------------------------------
return [
    // 指令定义
    'commands' => [
        // ...
        'swagger' => 'app\command\Swagger',
    ],
];

在 app/controller/Index.php 文件下测试使用

<?php

namespace app\controller;

use app\BaseController;
use OpenApi\Attributes as OA;

/**
 * @OA\Info(
 *     title="ThinkPHP API文档",
 *     version="1.0.0",
 *     description="API接口文档"
 * )
 * @OA\OpenApi(
 *     @OA\Server(
 *         url="http://localhost:8000",
 *         description="本地开发服务器"
 *     )
 * )
 */
class Index extends BaseController
{
    /**
     * @OA\Get(
     *     path="/",
     *     summary="首页接口",
     *     tags={"基础接口"},
     *     @OA\Response(
     *         response=200,
     *         description="成功返回首页内容",
     *         @OA\MediaType(
     *             mediaType="text/html"
     *         )
     *     )
     * )
     */
    public function index()
    {
        return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>';
    }
}

生成 swagger.json

 php think swagger

即可自动在 public 目录下新增 swagger.json 文件了,可以搭配 ApiFox 类的在线文档工具使用。

生产环境建议

该文档应该只放在开发环境,而不应该配置在生产环境中。

参考文章

# Swagger PHP Thinkphp 接口文档