Skip to content

Commit 736a070

Browse files
committed
Allow providing initial service definitions when creating CascadeContainer
1 parent 2fcab98 commit 736a070

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/CascadeContainer.php

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,11 +30,24 @@ final class CascadeContainer implements ContainerInterface
3030
/** @var array<string,string> */
3131
private array $aliases = [];
3232

33+
/**
34+
* @param ContainerInterface|array<string,mixed>|null $parent Parent container or initial service instances array map
35+
* @param DependencyResolverInterface|null $resolver
36+
*/
3337
public function __construct(
34-
ContainerInterface | null $parent = null,
35-
DependencyResolverInterface $resolver = null,
38+
ContainerInterface | array | null $parent = null,
39+
DependencyResolverInterface $resolver = null,
3640
) {
37-
$this->parent = $parent ?: new NullContainer();
41+
if (is_array($parent)) {
42+
foreach ($parent as $id => $instance) {
43+
if ( ! is_string($id)) {
44+
throw new InvalidArgumentException('The service ids have to be strings.');
45+
}
46+
$this->instances[$id] = $instance;
47+
}
48+
}
49+
50+
$this->parent = $parent instanceof ContainerInterface ? $parent : new NullContainer();
3851
$this->resolver = $resolver ?: new DependencyResolver($this);
3952
}
4053

tests/Feature/CascadeContainerTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,17 @@
1717
expect(new CascadeContainer($parent))->toBeInstanceOf(CascadeContainer::class);
1818
});
1919

20+
it('should construct a new instance with initial services', function () {
21+
$container = new CascadeContainer([
22+
'logger' => function (string $message) {
23+
echo $message, PHP_EOL;
24+
},
25+
]);
26+
27+
expect($container->has('logger'))->toBeTrue();
28+
expect($container->get('logger'))->toBeCallable();
29+
});
30+
2031
it('should construct a new instance of CascadeContainer with a custom resolver', function () {
2132
$resolver = new class implements DependencyResolver {
2233
public function resolve(string $className): mixed

0 commit comments

Comments
 (0)