Santi
Santi

Reputation: 509

config a listener to execute only in one bundle symfony 2

We need to configure a listener to check some registers in a db but we need to do this check action only in one bundle for every actions in it.

We don't want to call a function everytime we write a function in the bundle so we have thought to do a listener.

Does Symfony allow to configure a listener only in one bundle?

Thanks.

Upvotes: 4

Views: 3508

Answers (2)

user1954544
user1954544

Reputation: 1687

My case... I use event.controller, routes help me to 'use listener for custom routes'

Services

    kernel.listener.corporation.manage:
        class:  Site\CorporationBundle\Event\SiteCorporationManageListener
        arguments: ["@doctrine.orm.entity_manager"]
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Class

class SiteCorporationManageListener
{
    private $oEntityManager = null;

    public function __construct(EntityManager $oEntityManager)
    {
        $this->oEntityManager = $oEntityManager;
    }

    public function onKernelController(FilterControllerEvent $event)
    {
        if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
            // get variable from url if needed
            // $event->getRequest()->get('urlVariable', null); 
            $route = $event->getRequest()->get('_route');

            if (strstr($route, 'corporation')) {
                if (!strstr($route, 'corporation_index')) {
                    echo 'some request done';
                }
            }
        }
    }
}

Routes

corporation_index_default:
# . . .
corporation_api_default:
# . . .    
corporation_manage_default:
# . . .

In our case listener will work only in

corporation_api_default:
# . . .
corporation_manage_default:
# . . .

Upvotes: 0

Glen Swinfield
Glen Swinfield

Reputation: 638

You're thinking about this incorrectly. You can't configure a listener to execute for a bundle. In practice a listener just waits for its event to be fired -it's the event that defines when a listener gets called. What you really want to achieve is to fire an event before each action in your controller(s).

You could do this buy listening for the kernel.Controller event then doing something like this:

$controller = $event->getController();
if ($controller instanceof mybundlecontroller) {
    // fire custom event e.g. My.db.lookup
}
$event->setController($controller)

You can then have a separate listener that fires in this case.

See docs: http://symfony.com/doc/current/book/internals.html#kernel-controller-event

Upvotes: 4

Related Questions