2012-05-13 20 views
11

Sto cercando di usare Symfony2 e FOSRestBundle per creare un framework REST e sto fallendo miseramente.Impossibile lavorare con FOSRestBundle

Ho fatto quanto segue:

nel mio file 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 

Nei miei 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 

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


    } 
} 

Quando vado all'URL: http://local.symfony.com/web/app_dev.php/hello/test

ottengo:

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

La documentazione sembra confuso per me e io sono in grado di continuare. Tutto quello che voglio è essere in grado di passare una serie di dati al controller e recuperare un formato JSON. Qualcuno può aiutare?

+4

Ho anche problemi a ottenere questo andando. Sembra abbastanza confuso per quello che sembra un compito relativamente semplice. Hai avuto fortuna con esso? – greg

risposta

17

Nella sezione formats di config.yml è necessario abilitare il formato json e disabilitare altri formati e impostare il valore predefinito _format come json in rotta. per esempio

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

Oppure, nel controllore si può fare

$view->setFormat('json'); 

checkout anche l'esempio collegamenti fornite nella documentazione.

+3

Ha funzionato anche per me, ma solo quando uso un array come dati, cosa succede se voglio produrre un oggetto? – alex88

+1

Non funziona con le versioni più recenti. Una risposta più recente: http://stackoverflow.com/a/18035437/842697. I commenti sono molto interessanti. –