跳到内容

区域

编辑此页

我们已经看到,您可以使用 nelmio_api_doc.areas 配置要记录哪些路由

1
2
3
4
5
nelmio_api_doc:
    areas:
        path_patterns: [ ^/api ]
        host_patterns: [ ^api\. ]
        name_patterns: [ ^api_v1 ]

但实际上,此配置选项更加强大,允许您将文档拆分为多个部分。

配置

您可以定义区域,每个区域将生成不同的文档

1
2
3
4
5
6
7
8
9
10
11
12
nelmio_api_doc:
    areas:
        default:
            path_patterns: [ ^/api ]
            host_patterns: [ ^api\. ]
        internal:
            path_patterns: [ ^/internal ]
        commercial:
            path_patterns: [ ^/commercial ]
        store:
            # Includes routes with names containing 'store'
            name_patterns: [ store ]

您的主要文档位于 default 区域下。这是访问 /api/doc 时显示的文档。

然后更新您的路由,以便能够访问您的不同文档

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# app/config/routing.yaml
app.swagger_ui:
    path: /api/doc/{area}
    methods: GET
    defaults: { _controller: nelmio_api_doc.controller.swagger_ui, area: default }

# With Redocly UI
# app/config/routing.yaml
#app.redocly:
#    path: /api/doc/{area}
#    methods: GET
#    defaults: { _controller: nelmio_api_doc.controller.redocly, area: default }

# With Stoplight
# app/config/routing.yaml
#app.stoplight:
#    path: /api/doc/{area}
#    methods: GET
#    defaults: { _controller: nelmio_api_doc.controller.stoplight, area: default }

# To expose them as JSON
#app.swagger.areas:
#    path: /api/doc/{area}.json
#    methods: GET
#    defaults: { _controller: nelmio_api_doc.controller.swagger }

就这样!您现在可以访问 /api/doc/internal/api/doc/commercial/api/doc/store

使用属性来过滤每个区域中记录的路由

您可以在控制器内部使用 #[Areas] 属性来定义路由的区域。

首先,您需要定义哪些区域将使用 #[Areas] 属性来过滤应记录的路由

1
2
3
4
5
6
nelmio_api_doc:
    areas:
        default:
            path_patterns: [ ^/api ]
        internal:
            with_attribute: true

然后在您的控制器或操作之前添加属性/注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
use Nelmio\Annotation as Nelmio;

/**
 * @Nelmio\Areas({"internal"}) => All actions in this controller are documented under the 'internal' area
 */
class MyController
{
    /**
     * @Nelmio\Areas({"internal"}) => This action is documented under the 'internal' area
     */
    public function index()
    {
       ...
    }
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可获得许可。
目录
    版本