You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
How about having the Emitter implement the ContainerAware interface, so we can lazily fetch listeners from the container when we need them, instead of having to wire up a bunch of listeners which may never be needed for the current request?
classContainerAwareEmitterimplementsContainerAware
{
protectedfunctionensureListener($listener)
{
if ($listener instanceof ListenerInterface) {
return$listener;
}
if (is_callable($listener)) {
returnCallbackListener::fromCallable($listener);
}
if (is_string($listener)) {
returnLazyListener::fromAlias($this->container, $listener);
}
thrownewInvalidArgumentException('Listeners should be be ListenerInterface, Closure or callable, or an alias. Received type: '.gettype($listener));
}
}
classLazyListenerimplementsListenerInterface
{
/** * @var ContainerInterface */protected$container;
/** * @var string */protected$alias;
/** * @var ListenerInterface */protected$listener;
/** * @param ContainerInterface $container * @param string $alias */publicfunction__construct(ContainerInterface$container, $alias)
{
$this->container = $container;
$this->alias = $alias;
}
/** * Get the listener. * * @return ListenerInterface */publicfunctiongetListener()
{
if ($this->listener === null) {
try {
$listener = $this->container->get($this->alias);
} catch (\Exception$exception) {
thrownew \BadMethodCallException('Unable to fetch listener from container');
}
if (!$listener instanceof ListenerInterface) {
thrownew \BadMethodCallException('Fetched listener does not implement ListenerInterface');
}
$this->listener = $listener;
}
return$this->listener;
}
/** * {@inheritdoc} */publicfunctionhandle(EventInterface$event)
{
$this->getListener()->handle($event);
}
/** * {@inheritdoc} */publicfunctionisListener($listener)
{
if ($listener instanceof LazyListener) {
$listener = $listener->getListener();
}
return$this->listener === $listener;
}
/** * @param ContainerInterface $container * @param string $alias * @return static */publicstaticfunctionfromAlias(ContainerInterface$container, $alias)
{
returnnewstatic($container, $alias);
}
}
The text was updated successfully, but these errors were encountered:
Would also love to see this addition. If we're adding many events, we would rather not have to instantiate an instance of each listener and then pass them into the emitter. Rather, let us pass in a list of string aliases and have the container lazy load them when / if needed:
How about having the
Emitter
implement theContainerAware
interface, so we can lazily fetch listeners from the container when we need them, instead of having to wire up a bunch of listeners which may never be needed for the current request?The text was updated successfully, but these errors were encountered: