我想将 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。
要使用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)
就是这样!
在 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)
| 归档时间: |
|
| 查看次数: |
6609 次 |
| 最近记录: |