我正在使用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