Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute function on every route/Action in Symfony3

Tags:

symfony

I have a logging function that tracks pageloads. I would like to add that to every route that I already have in Symfony.

Currently I am doing it like this:

/**
 * @Route("/test", name="test")
 */
public function testAction(Request $request)
{


    /* Function to register pageload */
    $this->get('statsd')->countMetric('visitor.'.$request->get('_route'));


    return $this->render('default/indexFull.html.twig', array());

}

I could of course add that line to every route, but since I am new to Symfony I thought there might be a more elegant approach?

Any hint appreciated!

like image 558
PrimuS Avatar asked Mar 18 '26 01:03

PrimuS


1 Answers

Symfony triggers events during the handling of a request. One of these events is the kernel.request event, which is executed before each controller.

Be aware that the router will do the matching during this event as well, so you need to make sure your listener is executed after the router listener. This can be done by using priorities.

use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class CountMetricLogger
{
    // ...

    public function logVisit(GetResponseEvent $event)
    {
        $this->statsd->countMetric('visitor.'.$event->getRequest()->get('_route'));
    }
}
# app/config/services.yml
app.metric_logger:
    class: AppBundle\EventListener\CountMetricLogger
    arguments: ['@statsd']
    tags:
        - { name: kernel.event_listener, event: kernel.request, method: logVisit }

More information:

  • "The kernel.request Event"
  • "The EventDispatcher component"
  • "How to Create Event Listeners and Subscribers"
like image 79
Wouter J Avatar answered Mar 20 '26 20:03

Wouter J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!