diff --git a/src/Container.php b/src/Container.php index 678d2e2..14ca0cc 100644 --- a/src/Container.php +++ b/src/Container.php @@ -13,6 +13,13 @@ public function __construct(array $config = [], $selfName = '') { } } + public function connect(ProviderInterface $provider) { + $this->initializers[$provider->getName()] = function () use ($provider) { + $this->inject($provider); + return $provider->provide(); + }; + } + public function register($name, $initializer) { if ($initializer instanceof Value) { $this->services[$name] = $initializer->getValue(); diff --git a/src/DeclarerInterface.php b/src/DeclarerInterface.php index 7bed2ed..71914a5 100644 --- a/src/DeclarerInterface.php +++ b/src/DeclarerInterface.php @@ -1,5 +1,4 @@ get($serviceName); $this->assertEquals($name2, $service->getName(), 'Must return modified name'); } + + public function testConnect() { + $name = 'Luke Skywalker'; + $container = new Container( + [ + 'name' => $name, + ], + 'container' + ); + $provider = new LegacyProvider(); + $container->connect($provider); + $service = $container->get($provider->getName()); + $this->assertInstanceOf(LegacyService::class, $service, 'Must return instance of LegacyService'); + $this->assertEquals($name, $service->getName(), 'Must inject name from config'); + $this->assertEquals($container, $service->getContainer(), 'Must inject container by setter'); + } } diff --git a/tests/LegacyProvider.php b/tests/LegacyProvider.php new file mode 100644 index 0000000..b47a42c --- /dev/null +++ b/tests/LegacyProvider.php @@ -0,0 +1,32 @@ +autoDeclareDependencies(), ['name']); + } + + public function setName(string $name) { + $this->name = $name; + } + + public function getName(): string { + return 'helloWorld'; + } + + public function provide() { + return new LegacyService($this->name, $this->container); + } +} diff --git a/tests/LegacyService.php b/tests/LegacyService.php new file mode 100644 index 0000000..3fa4046 --- /dev/null +++ b/tests/LegacyService.php @@ -0,0 +1,22 @@ +name = $name; + $this->container = $container; + } + + public function getName(): string { + return $this->name; + } + + public function getContainer() { + return $this->container; + } +}