美文网首页
php安装swagger的一些事

php安装swagger的一些事

作者: 才不是小小喵 | 来源:发表于2020-04-08 15:10 被阅读0次
  • 这里以TP5(thinkPHP5)为例子
  1. 首先composer安装swagger-php
composer require zircote/swagger-php:2.0.*
  1. 安装swagger-ui 在安装swagger-ui的时候可以吧里面的dist文件夹整个拎出来放在public下
#github下载地址
https://github.com/swagger-api/swagger-ui.git
  • 我修改swagger目录下index.html文件里面的url
  • 我在PHP单独写了一个swagger控制器输出json是为了和yapi相结合此处也是为了测试
  • 其实可以不用单独写只要路径为swagger.json就可以了
<script>
    window.onload = function() {
      // Begin Swagger UI call region
      const ui = SwaggerUIBundle({
        url:"http://local.test.com/index/swagger/",
        // url:"../../application/swagger-docs/swagger.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
    }
  </script>
  1. 以TP5为例代码部分 这里我的处理方法是直接生成swagger.json
  • 注意坑的地方就要来了
namespace app\index\controller;

use Exception;
use think\Controller;
use Swagger\Annotations as SWG;

class Index extends Controller
{
/**
     * @SWG\Swagger(
     * schemes={"http"},
     * host="local.test.com",
     * basePath="/",
     * @SWG\Info(
     * title="API文档",
     * version="1.0.0",
     * )
     * )
     * @throws \think\Exception
     * 生成swagger.json文件
     */
    public function index()
    {
        $realpath = realpath(__DIR__ ."../../../");
        $swagger = \Swagger\scan($realpath);
        try {
            $swagger_path = $realpath."/swagger-docs/swagger.json";
            $res = file_put_contents($swagger_path, $swagger);
            return $res;
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }
    }
}

单独的读取json文件当然这里只是测试所以只是简单写了一点

namespace app\index\controller;


use think\Controller;

class Swagger extends Controller
{

    /**
     * 读取swagger.json并被调用
     * @return false|string
     */
    public function index()
    {
        $realpath = realpath(__DIR__ ."../../../");
        $swagger_path = $realpath."/swagger-docs/swagger.json";
        $swagger_data = file_get_contents($swagger_path);
        return $swagger_data;
    }


}
  1. 在上面进行输出的时候可能会出现以下报错 使用以下方法我个人的是解决了报错
  • ErrorException in Logger.php line 38:
    Required @SWG\Info() not found
  • 解决方法是用命令生成一个swagger.json 在项目 目录下执行
>php vendor\zircote\swagger-php\bin\swagger application\index\controller -o application\swagger-docs
  1. 完成展示
    此时swagger.json里面应该有数据
    image.png
    访问该连接应该会出现http://local.test.com/swagger/index.html
    image.png

相关文章

网友评论

      本文标题:php安装swagger的一些事

      本文链接:https://www.haomeiwen.com/subject/mkyzphtx.html