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

Mik*_*eGA 19 symfony

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

public function addAddressAction(Request $request)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

public function addAddressAction()
{
    $request  = $this->getRequest();
    ...
}
Run Code Online (Sandbox Code Playgroud)

哪一个更好?有关系吗?

Ahm*_*ani 43

如果您深入了解Symfony2 Base Controller代码,您可能会注意到getRequest()自版本2.4以来已被标记为已弃用,并将在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();
}
Run Code Online (Sandbox Code Playgroud)

通过以下演变介绍,

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

结论,

您的请求应该是您的行动签名的一部分.


ant*_*ony 12

据我所知,没有区别.无论如何,它都不会影响中断.即使您想在操作中指定所需的参数.例如

/**
 * @Route("/edit/{id}", name="edit")
 */
public function editAction(Request $request, $id)
{
    // Both $request and $id are available
}
Run Code Online (Sandbox Code Playgroud)