如何将请求传递给 Symfony2 中的控制器构造函数?

ACs*_*ACs -2 symfony

我想将 Request 对象传递给控制器​​构造函数,如下所示:

public function __construct(Request $request){
        $this->startGameSession($request);
}
Run Code Online (Sandbox Code Playgroud)

但我收到一个错误:

Catchable Fatal Error: Argument 1 passed to MyController::__construct() must be an instance of Symfony\Component\HttpFoundation\Request, none given...
Run Code Online (Sandbox Code Playgroud)

同样适用于动作,但不适用于 __construct。

yce*_*uto 5

要使用request实例,__constructor您需要将控制器定义为服务并注入request_stack服务(参考)。

控制器可以以与任何其他类相同的方式定义为服务。

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RequestStack;

class ServiceController extends Controller
{
    public function __construct(RequestStack $requestStack)
    {
        //do something with $requestStack->getCurrentRequest();
    }
}
Run Code Online (Sandbox Code Playgroud)

然后您可以将其定义为如下服务(自 Symfony 3.3 起,这可能不是必需的,因为自动装配):

# app/config/services.yml
services:
    service_controller:
        class: AppBundle\Controller\ServiceController
        arguments: ['@request_stack']
Run Code Online (Sandbox Code Playgroud)

您还可以在定义路由_controller值时使用相同的表示法路由到服务。要引用定义为服务的控制器,请使用单冒号 (:) 表示法。:

# app/config/routing.yml
index:
    path: /index
    defaults: { _controller: service_controller:indexAction }
Run Code Online (Sandbox Code Playgroud)

就是这样!

  • 最近控制器被定义为服务,因此不再需要服务定义。至少在3.4作品中是这样。这意味着在构造函数中将 RequestStack $requestStack 作为参数传递就足够了。 (2认同)

klo*_*oma 5

在 Symfony 控制器的最新版本(>3.4 - 从什么时候开始不确定)被注册为服务。 https://symfony.com/doc/current/controller/service.html

只需将RequestStack $requestStack作为构造函数中的参数传递。

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\RequestStack;

class MyController extends Controller
{
    public function __construct(RequestStack $requestStack)
    {
        $request = $requestStack->getCurrentRequest();
        //do something with the $request

    }
}
Run Code Online (Sandbox Code Playgroud)