2017-07-17 26 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