FOSRestBundle自定义视图处理程序未注册

时间:2016-07-19 10:28:40

标签: rest symfony csv fosrestbundle viewhandler

我正在尝试创建自定义处理程序,以便将响应序列化为csv格式。

到目前为止,我一直在遵循文档(http://symfony.com/doc/master/bundles/FOSRestBundle/2-the-view-layer.html#custom-handler)中的步骤,但是当使用.csv扩展名调用我的端点时,我仍然会收到错误:

The format "csv" is not supported for serialization.

这是我的services.yml配置位:

api.csv_handler:
    class: ApiBundle\ViewHandlers\CsvViewHandler

api.view_handler:
    parent: fos_rest.view_handler.default
    calls:
        - ["registerHandler", ["csv", ["@api.csv_handler", "createResponse"]]]

并在config.ymlfos_rest下我有:

view:
    mime_types: { 'csv': ['text/csv','text/plain'] }
    view_response_listener: 'force'
    formats:
        json: true
        xml:  true
        csv:  true
    templating_formats:
        html: true
format_listener:
    enabled: true
    rules:
        - { path: ^/, priorities: [ json, xml, csv ], fallback_format: json, prefer_extension: false }
        - { path: ^/api/doc, priorities: [ html ], fallback_format: html, prefer_extension: false }

createResponse类中的CsvViewHandler方法目前只包含一些调试代码,以验证它是否有效,但不是。

那我在这里错过了什么?

1 个答案:

答案 0 :(得分:3)

您必须在FOSRest捆绑包配置中注册视图处理程序:

fos_rest:
    ...
    service:
        view_handler: my_bundle.view_handler
    ...



services:
    ...
    my_bundle.my_handler:
        class: MyBundle\View\MyHandler
    my_bundle.view_handler:
        parent: fos_rest.view_handler.default
        calls:
            - ['registerHandler', [ 'my_format', ["@my_bundle.my_handler", 'createResponse'] ] ]
    ...