Newer
Older
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
<?php
namespace Hp\Patterns\ServiceLocator;
use InvalidArgumentException;
class ServiceLocator
{
private array $services = [];
private array $instantiated = [];
public function addInstance(string $class, ServiceInterface $service): void
{
$this->instantiated[$class] = $service;
}
public function addClass(string $class, array $params): void
{
$this->services[$class] = $params;
}
public function has(string $class): bool
{
return isset($this->instantiated[$class]) || isset($this->services[$class]);
}
public function get(string $class): ServiceInterface
{
if (isset($this->instantiated[$class])) {
return $this->instantiated[$class];
}
$object = new $class(...$this->services[$class]);
if (!$object instanceof ServiceInterface) {
throw new InvalidArgumentException();
}
$this->instantiated[$class] = $object;
return $object;
}
}