无法使用FOSRestBundle

时间:2012-05-13 17:30:59

标签: 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

在我的控制器中:

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);


    }
}

当我转到网址时: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

文档似乎让我感到困惑,我无法继续。我想要的是能够将一组数据传递给控制器​​并获得JSON格式。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:18)

formats的{​​{1}}部分中,您必须启用json格式并禁用其他格式,并将默认config.yml值设置为路径中的json。 e.g

_format

或者,在控制器中你可以做

# 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 }

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