-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContainer.php
More file actions
90 lines (78 loc) · 2.29 KB
/
Container.php
File metadata and controls
90 lines (78 loc) · 2.29 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php
namespace PluginFrame\Core\Services;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
/**
* A simple PSR-11–compatible service container.
* Implements a static singleton for global access.
*/
class Container implements ContainerInterface
{
/** @var Container|null */
private static ?Container $instance = null;
/** @var array<string, callable> */
private array $definitions = [];
/** @var array<string, mixed> */
private array $instances = [];
/** Private to enforce singleton */
private function __construct() {}
/**
* Retrieve the singleton instance.
*/
public static function getInstance(): Container
{
return self::$instance ??= new Container();
}
/**
* Bind a service ID to a resolver callable.
*
* @param string $id Service identifier.
* @param callable $resolver function(ContainerInterface): mixed
*/
public static function bind(string $id, callable $resolver): void
{
self::getInstance()->definitions[$id] = $resolver;
}
/**
* Resolve a service by its ID.
*
* @param string $id Identifier of the entry to look for.
* @return mixed The entry.
* @throws NotFoundExceptionInterface No entry was found for this identifier.
*/
public function get(string $id): mixed
{
if (isset($this->instances[$id])) {
return $this->instances[$id];
}
if (! isset($this->definitions[$id])) {
throw new class("Service {$id} not found")
extends \Exception
implements NotFoundExceptionInterface {};
}
$resolver = $this->definitions[$id];
$service = $resolver($this);
$this->instances[$id] = $service;
return $service;
}
/**
* Static shortcut to resolve a service.
*
* @param string $id
* @return mixed
*/
public static function resolve(string $id): mixed
{
return self::getInstance()->get($id);
}
/**
* Does this container have a resolver bound for $id?
*
* @param string $id Identifier to check.
* @return bool
*/
public function has(string $id): bool
{
return isset($this->definitions[$id]);
}
}