php - 无法使用 FOSRestBundle

标签 php rest symfony fosuserbundle

我正在尝试使用 Symfony2 和 FOSRestBundle 来构建 REST 框架,但失败得很惨。

我已完成以下操作:

在我的 deps 文件中:

[FOSRest]
    git=git://github.com/FriendsOfSymfony/FOSRest.git
    target=fos/FOS/Rest

[FOSRestBundle]
    git=git://github.com/FriendsOfSymfony/FOSRestBundle.git
    target=bundles/FOS/RestBundle

[JMSSerializerBundle]
    git=git://github.com/schmittjoh/JMSSerializerBundle.git
    target=bundles/JMS/SerializerBundle

在我的 apps/config.yml 中

fos_rest:
    view:
        formats:
            rss: true
            xml: false
        templating_formats:
            html: true
        force_redirects:
            html: true
        failed_validation: HTTP_BAD_REQUEST
        default_engine: twig


sensio_framework_extra:
    view:
        annotations: false

在我的 Controller 中:

namespace Rest\WebServiceBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;  


class DefaultController extends Controller
{

    public function indexAction($name)
    {


  $view = View::create()
          ->setStatusCode(200)
          ->setData($name);
        return $this->get('fos_rest.view_handler')->handle($view);


    }
}

当我访问 URL:http://local.symfony.com/web/app_dev.php/hello/test

我得到:

Unable to find template "".
500 Internal Server Error - InvalidArgumentException
2 linked Exceptions: Twig_Error_Loader » Twig_Error_Loader

该文档对我来说似乎很困惑,我无法继续。我想要的只是能够将数据数组传递到 Controller 并返回 JSON 格式。有人可以帮忙吗?

最佳答案

config.ymlformats 部分中,您必须启用 json 格式并禁用其他格式,并将默认 _format 值设置为路由中的 json 。例如

# app/config/config.yml
fos_rest:
    view:
        formats:
            json: true
            rss: false # removing them will also work
            xml: false
#.......

#bundle/routing.yml
route_name:
  pattern: /route
  defaults: { _controller: Bundle:Controller:Method, _format:json }

或者,在 Controller 中你可以这样做

$view->setFormat('json');

另请查看文档中给出的示例链接。

关于php - 无法使用 FOSRestBundle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10573764/

相关文章:

php - 何时在 Laravel 中使用 Eloquent 模型

rest - Docker API 返回 200 OK 然后 400 BAD REQUEST

forms - symfony 3 - 如何在表单中添加事件订阅者作为服务

php - 如何避免将 attr 应用于我选择字段的所有选项?

php - 正面回顾与匹配重置 (\K) 正则表达式功能

php - 如何以漂亮的方式将 web 转换为 pdf

rest - GWTP REST-Dispatch - 自从在 1.5 版本中删除了 Rest Service 接口(interface)之后,rest 调度的新用途是什么

symfony - Assetic Symfony2 less+compress 过滤器

php - 多个 CREATE TABLE 在一个事务中有错误 - 没有 PDO 异常

javascript - 如何更改 Extjs NodeInterface 上的 parentId 属性