在控制器中获取“请求"对象的最佳方法是什么?

在控制器中获取“请求

问题描述:

我已经看到请求对象作为参数传递给控制器​​操作方法,如下所示:

I have seen the request object being passed to the controller action method as a parameter like this:

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

我也在 action 方法中看到它从容器中获取:

I have also seen it within the action method where it is gotten from the container:

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

哪个更好?重要吗?

如果你深入了解 Symfony2 基础控制器代码,你可能会注意到 getRequest() 从 2.4 版本开始被标记为已弃用,并将在 3.0 中移除.>

If you take a deeper look at the Symfony2 Base Controller code, you may notice that getRequest() is marked as deprecated since version 2.4 and will be removed in 3.0.

/*
 * ...
 * @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();
}

由以下演变引入,

而且,这里是从 2.x 升级到 3.0 文档.

结论,

您的请求应该是您的操作签名的一部分.

Your Request should then be part of your action's signature.