Skip to content
This repository has been archived by the owner on Jan 21, 2020. It is now read-only.

Commit

Permalink
Always create alias for invokables
Browse files Browse the repository at this point in the history
The same behaviour we have in zend-servicemanager.
Proper configuration should be:

'invokables' => [
    Name\Service::class => Name\Service::class,
],

or when we want to use alias:

'invokables' => [
    'alias' => Name\Service::class,
],

then serivce will be available on:
- alias: $container->get('alias');
- class name: $container->get(Name\Service::class);
and it will be exactly the same instance.
  • Loading branch information
michalbundyra committed Feb 7, 2018
1 parent 63575dc commit 47587cb
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
8 changes: 5 additions & 3 deletions src/Config.php
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,13 @@ private function injectInvokables(Container $container, array $dependencies)
}

foreach ($dependencies['invokables'] as $name => $object) {
if (is_int($name)) {
$name = $object;
if ($name !== $object) {
$container[$name] = function (Container $c) use ($object) {
return $c->offsetGet($object);
};
}

$container[$name] = function (Container $c) use ($object) {
$container[$object] = function (Container $c) use ($object) {
return new $object();
};
}
Expand Down
22 changes: 21 additions & 1 deletion test/ConfigTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -335,7 +335,7 @@ public function testInjectMultipleDelegators()
);
}

public function testInvokablesWithoutAlias()
public function testInvokableWithAlias()
{
$dependencies = [
'invokables' => [
Expand All @@ -348,5 +348,25 @@ public function testInvokablesWithoutAlias()
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 testInvokableWithoutAlias()
{
$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);
}
}

0 comments on commit 47587cb

Please sign in to comment.