Skip to content

Commit

Permalink
fix: make sure everything had same instance
Browse files Browse the repository at this point in the history
Signed-off-by: Fery Wardiyanto <ferywardiyanto@gmail.com>
  • Loading branch information
feryardiant committed Jun 22, 2020
1 parent 54d9e53 commit 3955864
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Container.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ class Container implements ContainerInterface
*/
private $instances = [];

/**
* List of instances that been resolved.
*
* @var array<string, mixed>
*/
private $resolved = [];

/**
* Service container resolver.
*
Expand Down Expand Up @@ -52,10 +59,14 @@ public function get($id)
throw new NotFoundException($id);
}

if (isset($this->resolved[$id])) {
return $this->resolved[$id];
}

$instance = $this->instances[$id];

if (is_callable($instance)) {
return $this->resolver->handle($instance);
return $this->resolved[$id] = $this->resolver->handle($instance);
}

if (is_string($instance) && $this->has($instance)) {
Expand Down
28 changes: 28 additions & 0 deletions test/spec/Container.spec.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,4 +302,32 @@
$this->c->make([new Stubs\SomeClass(), 'shouldCalled'], ['new value'])
)->toEqual('new value');
});

it('Should have same instance everywhere', function () {
$this->c->set('foobar', function () {
return new class {
protected $items = [];
public function set($item, $value) {
$this->items[$item] = $value;
}
public function get($item) {
return $this->items[$item] ?? null;
}
};
});

$here = $this->c->get('foobar');
$here->set('key', 'value');

$there = $this->c->get('foobar');
$there->set('name', 'john');

$somewhere = $this->c->get('foobar');

foreach (['key', 'name'] as $key) {
expect($here->get($key))->toBe($there->get($key));
expect($there->get($key))->toBe($here->get($key));
expect($somewhere->get($key))->toBe($here->get($key));
}
});
});

0 comments on commit 3955864

Please sign in to comment.