E.Monogarov
E.Monogarov

Reputation: 467

Subscribe on Events by Event name prefix using Symfony EventDispatcher

Is it possible to listen all events by their name prefixes?

For example we have event kernel.componentName.eventName

Can I listen to any events with prefix kernel.componentName.* or something like that?

Upvotes: 1

Views: 157

Answers (1)

Federkun
Federkun

Reputation: 36964

You can do that in multiple ways. One of them is to call EventDispatcher#getListeners without any argument, get a list of all the event names that start with kernel.componentName. and subscribe to them one by one.

I think that the simpler way is to extends EventDispatcher.

use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event;

class MyEventDispatcher extends EventDispatcher
{
    protected function doDispatch($listeners, $eventName, Event $event)
    {
        // add logic here
        if (strpos($eventName, 'kernel.componentName.') === 0) {
            // do something, like call another listener or a callback
        }


        parent::doDispatch($listeners, $eventName, $event);
    }
}

Upvotes: 1

Related Questions