我正在使用FOSRestBundle,但我找不到如何拥有两个不同的端点,一个用于模板呈现(例如html/twig,/app ),另一个用于序列化(例如json,/api )。有可能吗?FOSRestBundle Automatic Route generation的文档没有指出任何这方面的内容。
使用Symfony 3和FOSRestBundle 2.x
发布于 2017-07-17 21:18:44
你可以通过你的app/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): View
{
return $this->container->get('doctrine')->getRepository('AppBundle:Brand')->findAll();
}
/**
* @Route("/", name="index")
*
* @return Response
*/
public function indexAction(Request $request): Response
{
return $this->render('@App/index.html.twig', [
'data' => $data,
]);
}
}干杯,
发布于 2017-09-21 13:52:38
只需在您的路由配置中指定prefix即可。
如果你正在使用YAML,你可以修改你的routing.yml文件:
app:
resource: '@AppBundle/Controller/'
type: annotation
prefix: /app
api:
type: rest
resource: AppBundle\Controller\RestController
prefix: /api现在,您的普通路由以/app开头,REST路由以/api开头
https://stackoverflow.com/questions/45134594
复制相似问题