From 736a070cf46bf4520fe5fb611770e4777319feea Mon Sep 17 00:00:00 2001 From: Ivan Voskoboinyk Date: Wed, 6 Aug 2025 18:29:11 +0200 Subject: [PATCH] Allow providing initial service definitions when creating CascadeContainer --- src/CascadeContainer.php | 19 ++++++++++++++++--- tests/Feature/CascadeContainerTest.php | 11 +++++++++++ 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/src/CascadeContainer.php b/src/CascadeContainer.php index 29f319d..b7e72e2 100644 --- a/src/CascadeContainer.php +++ b/src/CascadeContainer.php @@ -30,11 +30,24 @@ final class CascadeContainer implements ContainerInterface /** @var array */ private array $aliases = []; + /** + * @param ContainerInterface|array|null $parent Parent container or initial service instances array map + * @param DependencyResolverInterface|null $resolver + */ public function __construct( - ContainerInterface | null $parent = null, - DependencyResolverInterface $resolver = null, + ContainerInterface | array | null $parent = null, + DependencyResolverInterface $resolver = null, ) { - $this->parent = $parent ?: new NullContainer(); + if (is_array($parent)) { + foreach ($parent as $id => $instance) { + if ( ! is_string($id)) { + throw new InvalidArgumentException('The service ids have to be strings.'); + } + $this->instances[$id] = $instance; + } + } + + $this->parent = $parent instanceof ContainerInterface ? $parent : new NullContainer(); $this->resolver = $resolver ?: new DependencyResolver($this); } diff --git a/tests/Feature/CascadeContainerTest.php b/tests/Feature/CascadeContainerTest.php index 8cd1157..9b48f10 100644 --- a/tests/Feature/CascadeContainerTest.php +++ b/tests/Feature/CascadeContainerTest.php @@ -17,6 +17,17 @@ expect(new CascadeContainer($parent))->toBeInstanceOf(CascadeContainer::class); }); + it('should construct a new instance with initial services', function () { + $container = new CascadeContainer([ + 'logger' => function (string $message) { + echo $message, PHP_EOL; + }, + ]); + + expect($container->has('logger'))->toBeTrue(); + expect($container->get('logger'))->toBeCallable(); + }); + it('should construct a new instance of CascadeContainer with a custom resolver', function () { $resolver = new class implements DependencyResolver { public function resolve(string $className): mixed