FOSRestBundle 在 Symfony 4.1 中不起作用

FOSRestBundle doesn't work in Symfony 4.1

我在使用在 Symfony 4.1 项目下工作的 FOSRestBundle 返回视图时遇到问题。

这是来自我的控制器的代码:

class NewsController extends FOSRestController
{

    public function getNewsAction()
    {
        $data = ['news1', 'news2'];

        $view = $this->view($data, 200);

        return $this->handleView($view);
     }
}

fos_rest.yaml

fos_rest:
    param_fetcher_listener:  true
    allowed_methods_listener:  true
    routing_loader: true
    view:
        view_response_listener:  'force'
    format_listener:
        rules:
            - { path: ^/api, prefer_extension: true, fallback_format: json, priorities: [ json, html ] }

framework.yaml

framework:
    secret: '%env(APP_SECRET)%'
    php_errors:
        log: true

sensio_framework_extra:
    view:        { annotations: true }

所以我已经有了非常基本的配置,但我仍然遇到这样的错误:

(1/1) RuntimeException You must enable the SensioFrameworkExtraBundle view annotations to use the ViewResponseListener.

我试图删除 "view: view_response_listener: 'force'",但我遇到了这个错误:

An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface >must be injected in FOS\RestBundle\View\ViewHandler to render templates.

我为此苦苦挣扎了几个小时。是因为 Symfony 4 beta 状态吗?或者我做错了什么?也许我想念一些依赖?我在官方文档中找不到有关此问题的任何帮助。

You must enable the SensioFrameworkExtraBundle view annotations

sensio_framework_extra:
    view:        { annotations: false }

添加行到 config/packages/framework.yaml

framework:
    templating: { engines: ['twig'] }

它将解决

An instance of Symfony\Bundle\FrameworkBundle\Templating\EngineInterface >must be injected in FOS\RestBundle\View\ViewHandler to render templates.

您是否在请求中发送了 Accept: application/json

如果不是,你不一定需要twig,但你需要从bundle config中的格式配置中删除html

fos_rest:
    format_listener:
        rules:
            - { path: ^/, prefer_extension: true, fallback_format: json, priorities: [ json ] }

默认的优先级是html,这需要twig

Symfony 4.3 中的模板组件集成是 deprecated。因此 templating 部分必须从 config/packages/framework.yaml

中删除(或注释)
framework:
    # templating: { engines: ['twig'] }

要将 Twig 定义为 ViewHandler 中的模板服务,请将以下行添加到 config/services.yaml

    fos_rest.templating:
        alias: twig