Skip to content

Commit f0ba8ed

Browse files
committed
[DI] Container add subscribe() method to quick listen subscriber #883
1 parent ab7b916 commit f0ba8ed

3 files changed

Lines changed: 36 additions & 2 deletions

File tree

packages/di/src/Container.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@
3434
use Windwalker\DI\Exception\DefinitionResolveException;
3535
use Windwalker\DI\Exception\DependencyResolutionException;
3636
use Windwalker\DI\Wrapper\CallbackWrapper;
37+
use Windwalker\Event\EventListenableInterface;
38+
use Windwalker\Event\Provider\SubscribableListenerProviderInterface;
3739
use Windwalker\Utilities\Arr;
3840
use Windwalker\Utilities\Contract\ArrayAccessibleInterface;
3941
use Windwalker\Utilities\Wrapper\RawWrapper;
@@ -707,6 +709,38 @@ public function extend(string $id, Closure $closure, \UnitEnum|string|null $tag
707709
return $this;
708710
}
709711

712+
public function subscribe(
713+
string $id,
714+
object|array $subscriber,
715+
?int $priority = null,
716+
\UnitEnum|string|null $tag = null
717+
): static {
718+
return $this->extend(
719+
$id,
720+
function (object $instance) use ($priority, $subscriber) {
721+
if (
722+
$instance instanceof SubscribableListenerProviderInterface
723+
|| $instance instanceof EventListenableInterface
724+
) {
725+
if (is_object($subscriber)) {
726+
$instance->subscribe($subscriber, $priority);
727+
} else {
728+
if (array_is_list($subscriber)) {
729+
$subscriber = [$subscriber[0] => $subscriber[1]];
730+
}
731+
732+
foreach ($subscriber as $event => $handler) {
733+
$instance->on($event, $handler, $priority);
734+
}
735+
}
736+
}
737+
738+
return $instance;
739+
},
740+
$tag
741+
);
742+
}
743+
710744
/**
711745
* @param string $id
712746
*

packages/event/src/EventListenableInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public function subscribe(object $subscriber, ?int $priority = null): static;
3030
*
3131
* @param string $event
3232
* @param callable $callable
33-
* @param int $priority
33+
* @param int|null $priority
3434
*
3535
* @return static
3636
*

packages/event/src/Provider/SubscribableListenerProviderInterface.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ interface SubscribableListenerProviderInterface extends ListenerProviderInterfac
1717
*
1818
* @param string $event
1919
* @param callable $listener
20-
* @param int $priority
20+
* @param int|null $priority
2121
*
2222
* @return void
2323
*/

0 commit comments

Comments
 (0)