我有这个听众:
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpFoundation\Request;
class ControllerListener
{
public function onKernelController( FilterControllerEvent $event, Request $request )
{
if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
$controllers = $event->getController();
if (is_array( $controllers )) {
$controller = $controllers[0];
if (is_object( $controller )) {
if (method_exists( $controller, 'parControl' )) {
$controller->parControl(
$controller->getRequest(),
$controller->getRequest()->get( 'action' ),
$controller->getRequest()->get( 'context' ),
$controller->getRequest()->get( 'page' ),
$controller->getRequest()->get( 'case' ),
$controller->getRequest()->get( 'subset' )
);
}
if (method_exists( $controller, 'adminProjectControl' )) {
// to this method I need to pass Request $request
$controller->adminProjectControl($request);
}
if (method_exists( $controller, 'accessControl' )) {
$controller->accessControl();
}
}
}
}
}
public function onKernelResponse( FilterResponseEvent $event )
{
Utilities::flashDebugLoginMessage();
}
}
它被定义为services.yml
的服务:
pdone.listener.preexecute:
class: GroupDCA\PDOneBundle\Listener\ControllerListener
arguments: [@request]
public: true
scope: request
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }
- { name: kernel.event_listener, event: kernel.response, method: onKernelResponse }
但是由于我遇到了这三个错误,我应该做错了什么:
ControllerListener.php第12行中的ContextErrorException:可捕获 致命错误:参数2传递给 GroupDCA \ PDOneBundle \监听\ ControllerListener :: onKernelController() 必须是Symfony \ Component \ HttpFoundation \ Request的一个实例, 给出的字符串
ControllerListener.php第12行中的ContextErrorException:可捕获 致命错误:参数2传递给 GroupDCA \ PDOneBundle \监听\ ControllerListener :: onKernelController() 必须是Symfony \ Component \ HttpFoundation \ Request的一个实例, 给出的字符串
bootstrap.php.cache第3118行中的LogicException:没有侦听器 “kernel.exception”事件设置响应
那么,如何将请求注入侦听器?我能这样做吗?我也在这里发帖this,但没有得到如何做到这一点。
答案 0 :(得分:11)
FilterControllerEvent
已gives you access to the request:
public function onKernelController(FilterControllerEvent $event)
{
$request = $event->getRequest();
// ...
}
如果在事件未提供请求的侦听器中需要请求,请始终使用the request stack:
use Symfony\Component\HttpFoundation\RequestStack;
class MyService
{
private $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
public function doSomething()
{
$request = $this->requestStack->getCurrentRequest();
// ...
}
}
不推荐注入请求,我们会将其删除。 Request stack is the way to go。不要使用request
范围。
答案 1 :(得分:0)
您将请求对象从服务定义传递给ControllerListener构造函数,而不是传递给onKernelController方法。
取而代之的是:
protected $request;
public function __construct (Request $request) {
$this->request = $request;
}
哪个应该解决您的问题并使请求对象可用。