2014-01-08 56 views
16

我看到請求對象被傳遞到控制器的操作方法作爲像這樣的參數:在控制器中獲取'Request'對象的最佳方式是什麼?

public function addAddressAction(Request $request) 
{ 
    ... 
} 

我還發現它在那裏它被從容器得到的操作方法中:

public function addAddressAction() 
{ 
    $request = $this->getRequest(); 
    ... 
} 

哪一個更好?有關係嗎?

回答

43

如果你把在the Symfony2 Base Controller code從深層次看,你可能會注意到,自從2.4版本棄用,並將在3.0中被移除getRequest()標記。

/* 
* ... 
* @deprecated Deprecated since version 2.4, to be removed in 3.0. Ask 
*    Symfony to inject the Request object into your controller 
*    method instead by type hinting it in the method's signature. 
*/ 
public function getRequest() 
{ 
    return $this->container->get('request_stack')->getCurrentRequest(); 
} 

通過以下進化介紹,

而且,here'supgrade from 2.x to 3.0 documentation。然後

結論,

您的要求應該是你的行動簽名的一部分。

+0

我感謝你的出色答案,確實將容器的請求標記爲已棄用。 – MikeGA

10

據我所知,沒有區別。它不會以任何方式中斷影響。即使你想在你的動作中指定所需的參數。例如。

/** 
* @Route("/edit/{id}", name="edit") 
*/ 
public function editAction(Request $request, $id) 
{ 
    // Both $request and $id are available 
} 
+1

非常感謝。 – MikeGA

相關問題