可以使用ThinkPHP官方推荐的工具——Swagger自动生成API文档。具体步骤如下:
composer require --dev zircote/swagger-php
/**
* @SWG\Get(
* path="/user/{id}",
* tags={"用户"},
* summary="获取用户信息",
* @SWG\Parameter(
* name="id",
* in="path",
* description="用户ID",
* required=true,
* type="integer"
* ),
* @SWG\Response(
* response="200",
* description="用户信息",
* @SWG\Schema(
* type="object",
* @SWG\Property(
* property="id",
* type="integer",
* description="用户ID"
* ),
* @SWG\Property(
* property="name",
* type="string",
* description="用户名称"
* )
* )
* )
* )
*/
public function getUser($id)
{
// ...
}
use Swagger\Annotations as SWG;
/**
* @SWG\Swagger(
* schemes={"http"},
* host="api.example.com",
* basePath="/v1",
* @SWG\Info(
* version="1.0.0",
* title="API文档",
* description="API文档"
* )
* )
*/
class Index
{
/**
* @SWG\Get(
* path="/user",
* tags={"用户"},
* summary="获取用户列表",
* @SWG\Response(
* response="200",
* description="用户列表",
* @SWG\Schema(
* type="array",
* @SWG\Items(ref="#/definitions/User")
* )
* )
* )
*/
public function getUserList()
{
// ...
}
}
// 生成文档
$swagger = \Swagger\scan(__DIR__);
file_put_contents(__DIR__ . '/swagger.json', $swagger);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>API文档</title>
<link rel="stylesheet" href="https://cdn.staticfile.org/swagger-ui/3.40.0/swagger-ui.min.css">
<style>
html {
box-sizing: border-box;
overflow: -moz-scrollbars-vertical;
overflow-y: scroll;
}
*,
*:before,
*:after {
box-sizing: inherit;
}
body {
margin: 0;
background: #fafafa;
}
</style>
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://cdn.staticfile.org/swagger-ui/3.40.0/swagger-ui-bundle.min.js"></script>
<script src="https://cdn.staticfile.org/swagger-ui/3.40.0/swagger-ui-standalone-preset.min.js"></script>
<script>
window.onload = function () {
const ui = SwaggerUIBundle({
url: "./swagger.json",
dom_id: '#swagger-ui',
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
})
}
</script>
</body>
</html>
这样就可以在页面中显示生成的API文档了。