Skip to content

Commit b1459db

Browse files
authored
feat(container): allow to inject tagged singletons (#1544)
1 parent 14c3599 commit b1459db

File tree

4 files changed

+18
-3
lines changed

4 files changed

+18
-3
lines changed

packages/container/src/GenericContainer.php

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -419,13 +419,15 @@ private function autowire(string $className, mixed ...$params): object
419419
}
420420

421421
foreach ($classReflector->getProperties() as $property) {
422-
if ($property->hasAttribute(Inject::class) && ! $property->isInitialized($instance)) {
422+
$inject = $property->getAttribute(Inject::class);
423+
424+
if ($inject && ! $property->isInitialized($instance)) {
423425
if ($property->hasAttribute(Proxy::class)) {
424426
$property->set($instance, $property->getType()->asClass()->getReflection()->newLazyProxy(
425-
fn () => $this->get($property->getType()->getName()),
427+
fn () => $this->get($property->getType()->getName(), $inject->tag),
426428
));
427429
} else {
428-
$property->set($instance, $this->get($property->getType()->getName()));
430+
$property->set($instance, $this->get($property->getType()->getName(), $inject->tag));
429431
}
430432
}
431433
}

packages/container/src/Inject.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,7 @@
99
#[Attribute(Attribute::TARGET_PROPERTY)]
1010
final readonly class Inject
1111
{
12+
public function __construct(
13+
public ?string $tag = null,
14+
) {}
1215
}

packages/container/tests/ContainerTest.php

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -427,11 +427,13 @@ public function test_builtin_dependency_initializer(): void
427427
public function test_inject(): void
428428
{
429429
$container = new GenericContainer();
430+
$container->singleton(InjectB::class, $bTagged = new InjectB(), 'tagged');
430431

431432
/** @var InjectA $a */
432433
$a = $container->get(InjectA::class);
433434

434435
$this->assertInstanceOf(InjectB::class, $a->getB());
436+
$this->assertSame($bTagged, $a->getBTagged());
435437
}
436438

437439
public function test_unregister(): void

packages/container/tests/Fixtures/InjectA.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,16 @@
1111
#[Inject]
1212
private InjectB $b; // @phpstan-ignore-line
1313

14+
#[Inject('tagged')]
15+
private InjectB $bTagged; // @phpstan-ignore-line
16+
1417
public function getB(): InjectB
1518
{
1619
return $this->b;
1720
}
21+
22+
public function getBTagged(): InjectB
23+
{
24+
return $this->bTagged;
25+
}
1826
}

0 commit comments

Comments
 (0)