zircote/swagger-php是swagger的php版,是一个扩展库,我们需要安装使用
composer require zircote/swagger-php
window.onload = function() {
// Begin Swagger UI call region
const ui = SwaggerUIBundle({
url: "./openapi.json", //修改这里
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIStandalonePreset
],
plugins: [
SwaggerUIBundle.plugins.DownloadUrl
],
layout: "StandaloneLayout"
})
// End Swagger UI call region
window.ui = ui
}
<?php
require("vendor/autoload.php");
$gen = \OpenApi\Generator::class;
$openapi = $gen::scan([__DIR__.'/app/controller']);
//生成json, 可以用来对yapi的同步
file_put_contents(__DIR__.'/public/docs/openapi.json', $openapi->toJson());
//生成yaml
shell_exec("./vendor/bin/openapi ./app -o ./public/docs");
header("Location: /public/doc/index.html");
./app/controller代表生成文档时需要扫描的目录, ./public/docs是生成文档文件的位置(即生成openapi.json)
php swagger.php
我的建议是在nginx中配置swagger生成服务(swagger当作入口文件),nginx配置如下:
server {
listen 8788;
server_name localhost;
root "C:/phpstudy_pro/WWW/genesis/";
location / {
index swagger.php;
if ( -f $request_filename) {
break;
}
if ( !-e $request_filename) {
rewrite ^(.*)$ /public/docs/openapi.json last;
break;
}
}
location ~ \.php(.*)$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index admin.php;
fastcgi_split_path_info ^((?U).+\.php)(/?.+)$;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
fastcgi_param PATH_TRANSLATED $document_root$fastcgi_path_info;
include fastcgi_params;
}
}
在控制器中(app/controller)注释如下:
/**
class Report
{
/**
* @OA\Post(
* path="/add",
* summary="上报信息",
* description="上报信息接口",
* tags={"Report"},
* @OA\RequestBody(
* @OA\MediaType(
* mediaType="json",
* @OA\Schema(
* @OA\Property(
* property="device",
* type="int",
* description=" 0 未知 1 安卓 2 IOS ",
* ),
*
* messageData={"device": 1, "type": "startUp", "uuid": 12345678}
* )
* )
* ),
* @OA\Response(
* response=200,
* description="OK",
* @OA\MediaType(mediaType="json",
* @OA\Schema(
* @OA\Property(property="resultCode",type="string",description="返回code"),
* @OA\Property(property="resultInfo",type="string",description="返回错误信息"),
* @OA\Property(property="messageData",type="string",description="返回数据"),
* )
* )
* )
* )
*/
public function add(Request $request)
{
}
}
这个功能非常 N I C E