PeterD
PeterD

Reputation: 63

Symfony2: How to hook an event launched from a console command from different bundle

I have two different bundles.

In first one I've implemented a console command. I need, during command execution to launch an 'event' that could be listened by the second bundle 'cause I need to have custom logic to be performed.

First bundle must be decoupled from second bundle (first bundle must not have any reference for second bundle).

Thanks in advance.

Upvotes: 0

Views: 1507

Answers (2)

tomazahlin
tomazahlin

Reputation: 2167

In your first bundle, dispatch the event in the command as usual. When you dispatch an event, you also provide an unique name, along with the event dispatched.

In the second bundle, make a listener (class and yml/xml config), which will listen for the event with that unique name.

This way, the first bundle will not be aware of second bundle. If the second bundle does not exist, no listener will catch the event.

Now the only question is the event itself. I suggest you take a look at the GenericEvent.

http://symfony.com/doc/current/components/event_dispatcher/generic_event.html

Also, try not to pass in any objects which are defined in the first bundle, otherwise you will make second bundle dependent on first bundle. I would pass simple data, such as int,string,array.

Hope this helps.

Upvotes: 0

Milos Tomic
Milos Tomic

Reputation: 361

In first bundle command dispatch an event

<?php

namespace FirstBundle\Command;

class SomeCommand extends ContainerAwareCommand
{
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        // ...
        $this->getContainer()->get('event_dispatcher')->dispatch(
            'my.event'
            new GenericEvent($someData)
        );
        // ...
    }
}

that a listener from second bundle with catch

<?php

namespace SecondBundle\Listener;

class MyEventListener
{
    public functon onMyEvent(GenericEvent $event)
    {
        $data = $event->getSubject();
        // do something
    }
}

because he's subscribed to that event in service declaration

# SecondBundle/Resources/config/services.yml
services:
    second.my_event_listener:
        class: SecondBundle\Listener\MyEventListener
        tags:
            - { name: kernel.event_listener, event: my.event, method: onMyEvent }

Upvotes: 3

Related Questions