Skip to content

Commit

Permalink
add methods set and unset
Browse files Browse the repository at this point in the history
  • Loading branch information
Ondřej Ešler committed Nov 8, 2018
1 parent fe10d7b commit 4de0c45
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 1 deletion.
17 changes: 17 additions & 0 deletions spec/IW/ServiceContainerSpec.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,23 @@ function it_provides_aliased_service() {
$this->get(Service::class)->shouldBeAnInstanceOf(Service::class);
}

function it_can_be_injected_with_given_instance() {
$now = new \DateTime;
$this->set('now', $now);
$this->get('now')->shouldBe($now);
}

function it_can_be_injected_with_given_anything() {
$this->set('fb', ['foo' => 'bar']);
$this->get('fb')->shouldBe(['foo' => 'bar']);
}

function it_can_forget_injected_singleton() {
$this->set('fb', ['foo' => 'bar']);
$this->unset('fb');
$this->has('fb')->shouldReturn(false);
}

}

class Foo {}
Expand Down
31 changes: 30 additions & 1 deletion src/ServiceContainer.php
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,26 @@ public function bind(string $id, callable $factory): void
$this->factories[$id] = $factory;
}

/**
* Sets given entry as a singleton
*
* @param string $id ID of entry
* @param mixed $entry actual entry
*
* @return void
*/
public function set(string $id, $entry): void
{
$this->instances[$id] = $entry;
}

/**
* Mark particular ID to be a singleton, this is useful when global singletons
* are disabled but you still few.
*
* Note in good design you should not need much singletons
*
* @param string $id ID of singleton
* @param string $id ID of singleton to set
*
* @return void
*/
Expand All @@ -162,6 +175,22 @@ public function singleton(string $id): void
$this->instances[$id] = $this->get($id);
}

/**
* Unset a singleton with given ID, returns TRUE if singleton was set, FALSE otherwise
*
* @param string $id ID of singleton to unset
*
* @return bool
*/
public function unset(string $id): bool {
if (array_key_exists($id, $this->instances)) {
unset($this->instances[$id]);
return true;
}

return false;
}

private static function buildFactory($classname)
{
try {
Expand Down

0 comments on commit 4de0c45

Please sign in to comment.