Skip to content

Commit

Permalink
Merge pull request #1 from oliver-schoendorn/feature/add-alias-to-share
Browse files Browse the repository at this point in the history
Added alias argument to share method
  • Loading branch information
oliver-schoendorn authored Sep 5, 2017
2 parents 1b27c98 + 6fffceb commit 487f970
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
8 changes: 7 additions & 1 deletion Source/DependencyInjector.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,20 @@ public function __construct(ReflectionHandlerInterface $reflectionHandler, Logge
* The given class instance will be treated like a singleton (at least until overloaded).
*
* @param object $classInstance
* @param string|null $alias
*
* @return DependencyInjectorInterface
*/
public function share($classInstance): DependencyInjectorInterface
public function share($classInstance, string $alias = null): DependencyInjectorInterface
{
$classId = get_class($classInstance);
$this->logger->debug('Registered shared instance of class {classId}', [ 'classId' => $classId ]);
$this->sharedInstances[$classId] = $classInstance;

if ($alias) {
$this->alias($classId, $alias);
}

return $this;
}

Expand Down
3 changes: 2 additions & 1 deletion Source/DependencyInjectorInterface.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,11 @@ public function __construct(ReflectionHandlerInterface $reflectionHandler, Logge
* The given class instance will be treated like a singleton (at least until overloaded).
*
* @param object $classInstance
* @param string|null $alias
*
* @return DependencyInjectorInterface
*/
public function share($classInstance): DependencyInjectorInterface;
public function share($classInstance, string $alias = null): DependencyInjectorInterface;

/**
* Registers a new class id and a factory in order to create instances of the referenced class.
Expand Down
19 changes: 19 additions & 0 deletions Test/Unit/DependencyInjectorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,25 @@ public function testShare()
verify($shares[TestClass01::class])->same($instance);
}

public function testShareWithAlias()
{
verify($this->handler)->isInstanceOf(ReflectionHandlerInterface::class);
$alias = 'a random alias';
$instance = new TestClass01();
$di = new DependencyInjector($this->handler, $this->logger);
$accessor = new ClassAccessor($di);

verify($di->share($instance, $alias))->same($di);

$shares = $accessor->getProperty('sharedInstances');
verify(isset($shares[TestClass01::class]))->true();
verify($shares[TestClass01::class])->same($instance);

$aliases = $accessor->getProperty('aliases');
verify(isset($aliases[$alias]))->true();
verify($aliases[$alias])->equals(TestClass01::class);
}

public function testDelegate()
{
$delegate = function() {};
Expand Down

0 comments on commit 487f970

Please sign in to comment.