我正在使用FOSRestBundle,我無法找到兩個不同的端點,一個用於模板渲染(例如html/twig,/app
),另一個用於序列化(json,例如/api
)。可能嗎 ? FOSRestBundle Automatic Route generation的文檔並未指明任何這一點。FOSRestBundle的多根路由
使用的Symfony 3和FOSRestBundle 2.X
我正在使用FOSRestBundle,我無法找到兩個不同的端點,一個用於模板渲染(例如html/twig,/app
),另一個用於序列化(json,例如/api
)。可能嗎 ? FOSRestBundle Automatic Route generation的文檔並未指明任何這一點。FOSRestBundle的多根路由
使用的Symfony 3和FOSRestBundle 2.X
您可以在您的應用程序/ config.yml通過格式監聽器進行配置。
fos_rest:
format_listener:
rules:
- { path: '^/api', priorities: [json], fallback_format: json, prefer_extension: false }
- { path: '^/', priorities: ['text/html', '*/*'], fallback_format: html, prefer_extension: false }
param_fetcher_listener: force
view:
view_response_listener: force
formats:
json: true
html: true
關於路由部分,這裏的一個控制器與兩個動作,一個用於每個類型的響應的一個例子(註釋):
namespace RVW\AppBundle\Controller;
use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\View;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class BrandController extends FOSRestController
{
/**
* @param Request $request
* @View(statusCode=Response::HTTP_OK)
* @Route("/brands", name="brands")
* @Method({"GET"})
*
* @return View
*/
public function brandsAction(Request $request)
{
return $this->container->get('doctrine')->getRepository('AppBundle:Brand')->findAll();
}
/**
* @Route("/", name="index")
*
* @return Response
*/
public function indexAction(): Response
{
return $this->render('@App/index.html.twig', [
'data' => $data,
]);
}
}
乾杯,
只需指定在prefix
您的路由配置。
如果你使用YAML,你可以改變你routing.yml
文件:
app:
resource: '@AppBundle/Controller/'
type: annotation
prefix: /app
api:
type: rest
resource: AppBundle\Controller\RestController
prefix: /api
現在你的正常路線開始/app
和您的REST路線開始/api
謝謝!我在文檔中看到了,但路由部分呢?我找到了一種解決方法,我在'/ api'處定義了2個路由類型爲'rest:'的另一個路由器,並在'/ app'上定義了另一個具有非休息路由配置(加載控制器動作)的路由器,同時保留了相同的控制器 – Thiryn
該答案添加了有關路由的更多信息。只需返回fosrestview或在每個操作中呈現html視圖。如果您不使用註釋,則必須將其「轉換」爲routing.yml語法。 – sh4
@Thiryn如果解決了您的問題以解決問題,請接受答案。 – sh4