是否可以从不同的 class 或文件加载 Swagger 注释?

Is it possible to load Swagger annotations from a different class or file?

我有如下简单的 PHP 方法,如下所示

/**
*
* (swagger annotation to be called from a different class)
*
*/
public function getApiCall()
{
  //Do something
}

而且我需要在方法上方的注释中包含很长的 Swagger 文档,所以
是否可以将注释写在不同的 class 中? 并在此处用类似

的方式调用它
/**
*
*call('App\Http\Controllers\testAnnotation');
*/

主要目的是为了有一个干净的class,里面没有那么多行的文档和注释。

加载“来自不同 class 的注释”没有多大意义。在带注释的代码中读取注释,这就是它们的全部目的。

但是如果你想保持配置和代码分离,你不需要使用Swagger-Php来生成你的 swagger 配置文件。

该包只是一种从代码注释生成 swagger.json 文件的便捷方式。

但是,如果您一开始就不想使用注释,并且让您的 class 免受无关配置的影响(我个人对此表示赞赏),只是...不要使用 Swagger-Php 并在 classes.

之外构建您自己的配置文件

你甚至可以用 YAML 编写它,如果你觉得比手写 JSON 更舒服的话。例如::

openapi: 3.0.0
info:
  title: 'Search API'
  version: 1.0.0
servers:
- url: 
  description: Current host server
- url: https:your-server.com
  description: Prod server
paths:
  /foo:
    post:
      summary: 'Creates a new foo'
      description: 'Builds a new Foo and makes it available to Bar'
      requestBody:
        description: 'Foo '
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/Foo'
      responses:
        '201':
          description: Foo created
        '202':
          description: Foo queued, it will be eventually created.
components:
  schemas:
    Foo:
      type: object
      required:
      - name
      - size
      properties:
        name:
          type: string
        size:
          type: integer

这个,一旦转换为 JSON(有很多库可以做到这一点,或者您甚至可以使用免费服务 like this one),您可以将结果 JSON 提供给直接招摇

例如上面的 YAML 解析为 this JSON file. You can easily test it out by heading to the Swagger demo instance,并在“探索”位置栏中经过 JSON URL,您将得到如下内容:

最后,它并不比使用注释多多少工作(如果有的话),并且您可以使您的实体class远离配置问题。