2017-07-17 48 views

回答

1

您可以在您的应用程序/ 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, 
    ]); 
    } 
} 

干杯,

+0

谢谢!我在文档中看到了,但路由部分呢?我找到了一种解决方法,我在'/ api'处定义了2个路由类型为'rest:'的另一个路由器,并在'/ app'上定义了另一个具有非休息路由配置(加载控制器动作)的路由器,同时保留了相同的控制器 – Thiryn

+0

该答案添加了有关路由的更多信息。只需返回fosrestview或在每个操作中呈现html视图。如果您不使用注释,则必须将其“转换”为routing.yml语法。 – sh4

+0

@Thiryn如果解决了您的问题以解决问题,请接受答案。 – sh4

0

只需指定在prefix您的路由配置。

如果你使用YAML,你可以改变你routing.yml文件:

app: 
    resource: '@AppBundle/Controller/' 
    type:  annotation 
    prefix: /app 

api: 
    type:  rest 
    resource: AppBundle\Controller\RestController 
    prefix: /api 

现在你的正常路线开始/app和您的REST路线开始/api