2016-03-04 19 views
1

我正在嘗試設置我的應用程序,以便同樣的操作可以爲web和api返回響應。這個工作很棒,但有時候這個動作只需要網站而不是api。我正在尋找一種方法來啓用/禁用此功能每個操作/控制器。Symfony2 + FOSRestBundle + FrameworkExtraBundle在使用@Template時禁用休息和錯誤

我已經創建了兩個演示動作來測試,但一直無法讓一個不是對api url進行響應。

網站是通過domain.com訪問

API是通過api.domain.com訪問 - API的所有請求都使用格式聽者在配置

- { path: '^/', host: 'api.domain.dev', priorities: ['json'], fallback_format: ~, prefer_extension: false } 
JSON格式

第一個操作(indexAction)可以正常返回HTML和Json,具體取決於您使用的域。問題在於第二個操作(testAction),我希望這隻能在網站域上運行。訪問api.domain.com/company-test時,響應是模板HTML,其內容類型頭設置爲application/json。

當JSON版本不可用並且正在使用@Template時,是否有辦法使此返回錯誤(404?)?

測試操作

use FOS\RestBundle\Controller\Annotations as Rest; 
use FOS\RestBundle\View\View; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; 
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; 
use Nelmio\ApiDocBundle\Annotation\ApiDoc; 

/** 
* Get a list of companies 
* 
* @Rest\Get("/company") 
* @Rest\View(
*  template = "CompanyBundle:Company:index.html.twig", 
*  templateVar = "companies", 
*  statusCode = 200, 
*) 
* 
* @ApiDoc(
*  description="" 
*) 
*/ 
public function indexAction() { 
    $em = $this->getDoctrine()->getManager(); 

    $companies = $em->getRepository('CompanyBundle:Company')->findAll(); 

    $view = View::create(); 

    $view->setData($companies); 
    $view->setTemplateData(['extraData' => 'Hello World!']); 
    return $view; 
} 


/** 
* Get a list of companies 
* 
* @Route("/company-test") 
* 
* @ApiDoc(
*  description="" 
*) 
* 
* @Template(
*  template="CompanyBundle:Company:index.html.twig" 
*) 
*/ 
public function testAction() { 
    $em = $this->getDoctrine()->getManager(); 

    $companies = $em->getRepository('CompanyBundle:Company')->findAll(); 

    return [ 
     'companies' => $companies, 
     'test-test' => 'Hello World!' 
    ]; 
} 

回答

0

我想你可以從SensioFrameworkExtraBundle延長TemplateListener和修改 「onKernelView」 https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/EventListener/TemplateListener.php#L77

創建你自己的監聽器MyBundle \ EvetListener \ MyListener.php擴展原有TemplateListener,然後你可以整個onKernelView的方法和chanage https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/EventListener/TemplateListener.php#L83

if (null === $template) { 
     return; 
    } elseif($this->getRequest()->getHost() == $this->container->getParameter('api_domain')) { // %api_domain% should be filled at parameters.yml  
     $event->setResponse(new JsonResponse(NULL, Response::HTTP_NOT_FOUND)); // don't forget to add "use Symfony\Component\HttpFoundation\JsonResponse" 
     return; 
    } 

覆蓋服務參數https://github.com/sensiolabs/SensioFrameworkExtraBundle/blob/master/Resources/config/view.xml#L8

<parameters> 
     <parameter key="sensio_framework_extra.view.listener.class">MyApp\EventListener\MyListener</parameter> 
</parameters> 

或通過陽明如果你使用XML的陽明而不是爲服務配置

+0

這正是我需要的。謝謝! – user6020259