Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 event listener

Tags:

php

symfony

So, I'm trying to figure out these listeners but I'm having issues finding any information on the symfony site regarding them..

Initially, I wanted to create a listener that would trigger on every page load... I figured that could be detrimental to the overall system performance so i then thought of having it trigger only on: / and /otherpage

But again, i'm having issues finding any information on where to get started with the listener. Any help appreciated.. All this listener will be doing, is using Doctrine to check the database and setting a session based on what it finds..

Again, any help or suggestions appreciated. Thanks.

like image 678
Justin Avatar asked May 29 '12 21:05

Justin


1 Answers

I do something similar to check the subdomain hasn't changed. You can put the listener in as a service in your config file as follows:

services:
    page_load_listener:
        class: Acme\SecurityBundle\Controller\PageLoadListener
        arguments: 
            security: "@security.context", 
            container: "@service_container"
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: 64 }

I'm not exactly sure how priority works but I've found if it's set too high it wouldn't run before the rest of the application. It's on my to-do list to research a little more.

Here is an example of how the listener could look.

namespace Acme\SecurityBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;

class PageLoadListener extends controller
{
    private $securityContext;
    protected $container;
    protected $query;

    public function __construct(SecurityContext $context, $container, array $query = array())
    {
        $this->securityContext = $context;
        $this->container = $container;
        $this->query = $query;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {       
        //if you are passing through any data
        $request = $event->getRequest();

        //if you need to update the session data
        $session = $request->getSession();              

        //Whatever else you need to do...

    }
}

I'm not sure of the best way to set it to only run on certain pages, but my best guess would be to check the route and only hit your db it when the route matches whatever you set.

Hope that gets you started!

Greg

like image 190
greg Avatar answered Oct 04 '22 00:10

greg