diff --git a/README.md b/README.md index 6f1ce55..f0f2cec 100644 --- a/README.md +++ b/README.md @@ -49,8 +49,8 @@ The `dependencies` sub associative array can contain the following keys: - `services`: an associative array that maps a key to a specific service instance. - `invokables`: an associative array that map a key to a constructor-less service; i.e., for services that do not require arguments to the constructor. - The key and service name may be the same; if they are not, the name is treated - as an alias. + The key and service name usually are the same; if they are not, the key is + treated as an alias. - `factories`: an associative array that maps a service name to a factory class name, or any callable. Factory classes must be instantiable without arguments, and callable once instantiated (i.e., implement the `__invoke()` method). diff --git a/src/Config.php b/src/Config.php index 3ec3929..1b38107 100644 --- a/src/Config.php +++ b/src/Config.php @@ -83,7 +83,13 @@ private function injectInvokables(Container $container, array $dependencies) } foreach ($dependencies['invokables'] as $name => $object) { - $container[$name] = function (Container $c) use ($object) { + if ($name !== $object) { + $container[$name] = function (Container $c) use ($object) { + return $c->offsetGet($object); + }; + } + + $container[$object] = function (Container $c) use ($object) { return new $object(); }; } diff --git a/test/ConfigTest.php b/test/ConfigTest.php index 842050b..cff96b6 100644 --- a/test/ConfigTest.php +++ b/test/ConfigTest.php @@ -334,4 +334,39 @@ public function testInjectMultipleDelegators() $service->injected ); } + + public function testInvokableWithoutAlias() + { + $dependencies = [ + 'invokables' => [ + TestAsset\Service::class, + ], + ]; + + (new Config(['dependencies' => $dependencies]))->configureContainer($this->container); + + self::assertTrue($this->container->offsetExists(TestAsset\Service::class)); + $service = $this->container->offsetGet(TestAsset\Service::class); + self::assertInstanceOf(TestAsset\Service::class, $service); + self::assertTrue($this->container->offsetExists('0')); + } + + public function testInvokableWithAlias() + { + $dependencies = [ + 'invokables' => [ + 'alias' => TestAsset\Service::class, + ], + ]; + + (new Config(['dependencies' => $dependencies]))->configureContainer($this->container); + + self::assertTrue($this->container->offsetExists('alias')); + $service = $this->container->offsetGet('alias'); + self::assertInstanceOf(TestAsset\Service::class, $service); + self::assertTrue($this->container->offsetExists(TestAsset\Service::class)); + $originService = $this->container->offsetGet(TestAsset\Service::class); + self::assertInstanceOf(TestAsset\Service::class, $originService); + self::assertSame($service, $originService); + } }