简体   繁体   English

无法在Symfony2中使用事件侦听器将参数获取到控制器

[英]Cannot get parameters to controller using event listener in Symfony2

I am currently using the Symfony2 event listener to change the controller to a different one based on a users authentication status. 我目前正在使用Symfony2事件侦听器根据用户身份验证状态将控制器更改为其他控制器。 I get the listener to set the new controller but it is instantiated without the container parameter (ie $this->container returns null). 我让侦听器设置了新的控制器,但是没有容器参数对其进行了实例化(即$ this-> container返回null)。

Is there anyway to pass the container on to the controller I am changing to? 是否有将容器传递到我要更改的控制器的方法?

class AuthenticationListener
{
  public function onController(FilterControllerEvent $event)
  {
    $request = $event->getRequest();
    $session = $request->getSession();
    if (!$session->has('authenticated') || $session->get('authenticated') === false)
    {
      $controller = $event->getController();

      if (!($controller[0] instanceof AuthenticateController) && !($controller[0] instanceof ExceptionController))
      {
        $event->setController(array(new AuthenticateController(), 'loginAction'));
      }
    }
  }
}

The container is not set, when you create the controller automatically. 自动创建控制器时,未设置容器。 Call setContainer after constructing the controller. 构造控制器后,调用setContainer。 Afterwards you can pass it to the event. 之后,您可以将其传递给事件。

In this case AuthenticationListener its just a class 在这种情况下,AuthenticationListener只是一个类

if you want to use $this->container in this class you must do like this: 如果要在此类中使用$ this-> container,则必须这样做:

class BeforeControllerListener extends ContainerAware
{
...
}

and in config.yml 并在config.yml中

core.listener.before_controller:
    class: App\YourBundle\EventListener\YourListener
    tags: [ {name: kernel.event_listener, event: kernel.controller, method: onKernelController}]
    calls:
        - [ setContainer,[ @service_container ]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM