2016-11-24 57 views
0

我試圖路線symfony的一個URL,URL來進行匹配有3個變種使用可選參數的Symfony路由陽明文件

/test/param1/test.json 
/test/param1/param2/test.json 
/test/param1/param2/param3/test.json 

我想用一個單一的控制器和參數2和參數3要做到這一點是可選參數。

我試過要求 param2和param3允許一個字符串和任何東西,但我不能讓所有3路徑匹配去同一個控制器。

感謝

+1

我看到的更簡單的方法是聲明3條路線指向同一動作 – OlivierC

回答

0

你可以做的是定義不同的路由,並分配到一個控制器,操作:

testparam123: 
    pattern: /test/{param1}/{param2}/{param3}/test.json 
    defaults: { _controller: Bundle:Controller:test} 
testparam12: 
     pattern: /test/{param1}/{param2}/test.json 
     defaults: { _controller: Bundle:Controller:test} 
testparam1: 
     pattern: /test/{param1}/test.json 
     defaults: { _controller: Bundle:Controller:test} 

然後你就位指示操作方法看起來像

public function testAction($param1,$param2=NULL,$param3=NULL) { 
    // do something 
} 

希望這有助於

0

這不適用於一個路由配置。如果PARAMS應該是可選的,那麼你就必須離開查詢參數空像

/test/param1/param2//test.json 

這裏的symfony知道參數3爲空。否則,你永遠不知道該URL的一部分是空的,因爲你可以把這樣的:

/test/param1/param3/test.json

應該如何Symfony的認識到,參數2缺失和參數3而不是給出? 你可以邏輯從

/test/param1/param2/param3/test.json 

改變

/test/param1-param2-param3-test.json 

那好辦了。

+0

我認爲CiTNOH的解決方案不會匹配: – Rawburner

+0

/test/param1/param3/test.json – Rawburner

1

您只能使用一個允許「/」的路由參數,然後在控制器中拆分參數。事情是這樣的:

_test: 
    path:  /test/{params}/test.json 
    defaults: { _controller: AppBundle:Demo:test } 
    requirements: 
     params: .+ 

而且控制器:

public function testAction(Request $request, $params) 
{ 
    dump($params); // param1/param2/param3 
    $paramsArray = split("/", $params); 
} 

這對對子級任意數量的參數工作!