我正在嘗試設置我的應用程序,以便同樣的操作可以爲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!'
];
}
這正是我需要的。謝謝! – user6020259