简体   繁体   中英

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. I get the listener to set the new controller but it is instantiated without the container parameter (ie $this->container returns 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. Afterwards you can pass it to the event.

In this case AuthenticationListener its just a class

if you want to use $this->container in this class you must do like this:

class BeforeControllerListener extends ContainerAware
{
...
}

and in 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 ]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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