-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Container.php
61 lines (49 loc) · 1.41 KB
/
Container.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
declare(strict_types=1);
namespace SonsOfPHP\Component\Container;
use Psr\Container\ContainerInterface;
use SonsOfPHP\Component\Container\Exception\ContainerException;
use SonsOfPHP\Component\Container\Exception\NotFoundException;
/**
* Usage:
* $container = new Container();
* $container->set('service.id', function (ContainerInterface $container) {
* return new Service($container->get('another.service_id'));
* });
*/
class Container implements ContainerInterface
{
private array $services = [];
private array $cachedServices = [];
/**
* {@inheritdoc}
*/
public function get(string $id)
{
if (false === $this->has($id)) {
throw new NotFoundException(sprintf('Service "%s" not found.', $id));
}
if (!array_key_exists($id, $this->cachedServices)) {
$this->cachedServices[$id] = call_user_func($this->services[$id], $this);
}
return $this->cachedServices[$id];
}
/**
* {@inheritdoc}
*/
public function has(string $id): bool
{
return array_key_exists($id, $this->services);
}
/**
* @param callable $callable
*/
public function set(string $id, $callable): self
{
if (!is_callable($callable)) {
throw new ContainerException('MUST pass in a callable');
}
$this->services[$id] = $callable;
return $this;
}
}