Isaac Bosca
Isaac Bosca

Reputation: 1648

Execute some code before Controller in every request on Symfony3

I need to execute some code before Symfony 3 controllers are executed.

I read this guide: http://symfony.com/doc/current/event_dispatcher/before_after_filters.html that explains how to do it.

But in this point: http://symfony.com/doc/current/event_dispatcher/before_after_filters.html#tag-controllers-to-be-checked the documentation explains that we need to specify what controllers will be affected by this EventListener using implements TokenAuthenticatedController on each Controller we need, but since I want to execute code before every controller (all), I hope that exists some way to do it without add the implements on all my Controllers.

Upvotes: 3

Views: 3152

Answers (2)

gp_sflover
gp_sflover

Reputation: 3500

In the example showed in the docs, the interface TokenAuthenticatedController is used only to execute specific code on all controllers that implements that interface to prevent to be execuded on every request in all controllers.

keep in mind that maybe you need to check if you really want to execute the code in every request type or only in predefined type like master requests as described in Events and Event Listeners.

Upvotes: 2

Joe
Joe

Reputation: 2436

Do you really need to execute the code on every request? Then maybe you should rather look at the available KernelEvents (especially kernel.request and kernel.controller). Go to: http://symfony.com/doc/current/components/http_kernel.html for more details like main and sub-requests.

Also your controllers don't actually need to implement anything. The TokenAuthenticatedController is only implemented in the example to execute:

if ($controller[0] instanceof TokenAuthenticatedController) {
        $token = $event->getRequest()->query->get('token');
        if (!in_array($token, $this->tokens)) {
            throw new AccessDeniedHttpException('This action needs a valid token!');
        }
    }

If you don't intend to do anything with the controller in your listener and do some other stuff you can just do whatever you like, given everything you need to do your work is injected into the listener and available at that point.

Edit from the docs:

A kernel.controller listener gets notified on every request, right before the controller is executed. So, first, you need some way to identify if the controller that matches the request needs token validation.

If you want to execute your code regardless of which controller is finally executed you don't need the before mentioned way to identify which controller will be executed therefore is no need for the interface at all.

Upvotes: 5

Related Questions