无法使用FOSRestBundle

jin*_*ini 12 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
Run Code Online (Sandbox Code Playgroud)

在我的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
Run Code Online (Sandbox Code Playgroud)

在我的控制器中:

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


    }
}
Run Code Online (Sandbox Code Playgroud)

当我转到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
Run Code Online (Sandbox Code Playgroud)

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

Mun*_*Das 18

formats部分中,config.yml您必须启用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 }
Run Code Online (Sandbox Code Playgroud)

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

$view->setFormat('json');
Run Code Online (Sandbox Code Playgroud)

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

  • 它也适用于我,但只有当我使用数组作为数据时,如果我想输出一个对象怎么办? (3认同)