RR404
RR404

Reputation: 686

symfony2: How to create a listener that's being invoked before any other listener?

I'd like to perform a redirect before any listener is invoked.

Specifically before the oauthListener of hwi kicks in.

The reason why i want to do that:

Am i doing it totally wrong ? If i want to go on, do you know how i should declare my listener so that it comes first AND has the ability to trigger an immediate redirect ?

Upvotes: 1

Views: 461

Answers (2)

RR404
RR404

Reputation: 686

Indeed this was it.

I tried it a few times and thought it did not work but that probably was a problem of cache clearing.

So then, for those who'd like to know : I process my data in order to create a RedirectResponse (Symfony\Component\HttpFoundation\RedirectResponse)

and within onKernelRequest i do

public function onKernelRequest(GetResponseEvent $event){
    /**
      ... do stuff here
    */

    $event->setResponse($myResponse);
}

Upvotes: 0

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52513

The kernel.request event is the first event that is being dispatched.

Have a look at the list of KernelEvents.

To have your specific listener executed before the other kernel.request listeners you can add the priority option (range: -255 to 255,highest executed first) to your listener's service configuration.

example:

services:
    kernel.listener.your_listener_name:
        class: Acme\DemoBundle\EventListener\AcmeRequestListener
        tags:
            - name: kernel.event_listener
              event: kernel.request
              method: onKernelRequest
              priority: 255

Now all that's left for you is to perform the redirect under certain conditions inside the listener's onKernelRequest() method.

I'm sure you'll figure out how to do that. A complete code example would be out of the scope of this question.

More instructions on how to write a kernel event listener can be found in the documentation chapter:

"How to create an Event Listener"

Upvotes: 1

Related Questions