【问题标题】:FOSRestBundle doesn't work in Symfony 4.1FOSRestBundle 在 Symfony 4.1 中不起作用
【发布时间】:2017-11-27 13:37:28
【问题描述】:

在 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) 运行时异常 您必须启用 SensioFrameworkExtraBundle 视图注释才能使用 ViewResponseListener。

我试图删除“view:view_response_listener:'force'”,但后来我遇到了这个错误:

一个 Symfony\Bundle\FrameworkBundle\Templating\EngineInterface 的实例 >必须注入 FOS\RestBundle\View\ViewHandler 来渲染模板。

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

【问题讨论】:

  • 可能与this 有关,顺便说一句,4.1 将是主开发版本。 4.0 仅处于发布候选阶段。
  • 并且根据bundle compatibility spreadsheet fosrestbundle 还不支持4.x。没有什么大惊喜。

标签: php symfony fosrestbundle


【解决方案1】:

将行添加到config/packages/framework.yaml

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

会解决的

一个 Symfony\Bundle\FrameworkBundle\Templating\EngineInterface 的实例 >必须注入 FOS\RestBundle\View\ViewHandler 来渲染模板。

【讨论】:

  • 它可以工作,但我不明白的是,我已经在我的项目中使用了 twig。为什么要在 ViewHandler 中使用泛型 framework-config 时必须添加?
【解决方案2】:

您是否在请求中发送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.1 解决了我的问题。
  • 这应该是正确答案!如果你想对所有路由使用 json 响应,规则 {fallback_format: json} 就足够了!
【解决方案3】:

您必须启用 SensioFrameworkExtraBundle 视图注释

sensio_framework_extra:
    view:        { annotations: false }

【讨论】:

  • 对不起,我复制粘贴的错误。它不适用于真假值。
【解决方案4】:

模板组件集成在 Symfony 4.3 中是 deprecated。所以 templateing 部分必须从 config/packages/framework.yaml 中删除(或注释)

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

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

 fos_rest.template:
        别名:树枝

【讨论】:

  • 这与问题有什么关系?
  • Alexander Matrosov 建议在配置中添加模板行以解决问题中的最后一个错误(我现在无法添加评论答案)。但它在 Symfony 4.3 中已被弃用。
猜你喜欢
  • 1970-01-01
  • 2021-04-11
  • 1970-01-01
  • 1970-01-01
  • 2018-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
相关资源
最近更新 更多