2012-08-09 27 views
5

我的應用程序的一部分將作爲API提供,因此我的一些頁面需要以JSON或XML(基於Accept標頭的「內容類型」)提供。Symfony2 + FOSRestBundle:啓用/禁用每個控制器/操作的REST功能?

我用FOSRestBundle和發送Accept頭「內容類型:應用程序/ XML」,當它工作得很好,但現在ALL我的網頁是在XML(或JSON)可用。

所以,我想爲我的一些控制器/操作啓用/禁用此功能。我會理想的做到這一點使用註釋。

這可能嗎?

我config.yml:

fos_rest: 
    view: 
     formats: 
      rss: false 
      xml: true 
      json: true 
     templating_formats: 
      html: true 
     force_redirects: 
      html: false 
     failed_validation: HTTP_BAD_REQUEST 
     default_engine: twig 
     view_response_listener: force 
    body_listener: 
     decoders: 
      json: acme.decoder.json 
      xml: fos_rest.decoder.xml 
    format_listener: 
     default_priorities: ['html', 'xml', 'json', '*/*'] 
     fallback_format: html 
     prefer_extension: false  

回答

6

the RestBundle's documentation,你不會,如果你不你的控制器使用View獲取XML輸出。因此,如果您在動作中不使用@View註釋或View::create(),並且您返回經典響應,則會得到HTML輸出。

如果要強制格式因爲某些原因,你可以把prefer_extensiontrue和調整路由定義:

my_route: 
    pattern: /my-route 
    defaults: { _controller: AcmeDemoBundle:action, _format: <format> } 

哪裏<format>是要強制格式。

2

您可以將view_response_listener設置爲false(默認爲force)。然後將@View註釋添加到您要使用REST的每個控制器類。

例子會使它更清晰。

而不REST甲CONTROLER:

/** 
* @Route("/comments") 
*/ 
class CommentsControler extends Controller 
{ 
    /** 
    * @Route("/") 
    * @Method({"POST"}) 
    */ 
    public function newAction() { ... } 

    /** 
    * @Route("/{id}") 
    */ 
    public function detailAction($id) { ... } 

    ... 
} 

並與REST另一個控制器。請注意,只需要@View該類的註釋(除非您想覆蓋響應狀態碼)。

/** 
* @View 
* @Route("/api/comments") 
*/ 
class RestfulCommentsControler extends Controller 
{ 
    /** 
    * @Route("/") 
    * @Method({"POST"}) 
    */ 
    public function newAction() { ... } 

    /** 
    * @Route("/{id}") 
    */ 
    public function detailAction($id) { ... } 

    /** 
    * @View(statusCode=204) 
    * @Route("/{id}/delete") 
    */ 
    public function deleteAction($id) { ... } 

    ... 
} 
  • ViewFOS\RestBundle\Controller\Annotations\View
  • RouteSymfony\Component\Routing\Annotation\Route
+1

聽起來很不錯,但它似乎並沒有工作。 – 2012-08-30 14:44:47

+0

它適合我。你使用了正確的'View'註解類嗎?你能提供更多信息嗎? – 2012-09-13 23:05:09

+1

如果您使用FOS \ RestBundle \ Controller \ Annotations作爲Rest;',您的註釋應該是@Rest \ View而不是'@ View' – alexismorin 2013-08-02 17:54:44

相關問題