forked from fa/breadcrumb-the-shire
39 lines
912 B
PHP
39 lines
912 B
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace MintyPHP\App;
|
||
|
|
|
||
|
|
use RuntimeException;
|
||
|
|
|
||
|
|
final class AppContainer
|
||
|
|
{
|
||
|
|
/** @var array<string, callable(self): mixed> */
|
||
|
|
private array $bindings = [];
|
||
|
|
|
||
|
|
/** @var array<string, mixed> */
|
||
|
|
private array $instances = [];
|
||
|
|
|
||
|
|
public function set(string $id, callable $factory): void
|
||
|
|
{
|
||
|
|
$this->bindings[$id] = $factory;
|
||
|
|
}
|
||
|
|
|
||
|
|
public function has(string $id): bool
|
||
|
|
{
|
||
|
|
return array_key_exists($id, $this->instances) || array_key_exists($id, $this->bindings);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function get(string $id): mixed
|
||
|
|
{
|
||
|
|
if (array_key_exists($id, $this->instances)) {
|
||
|
|
return $this->instances[$id];
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!array_key_exists($id, $this->bindings)) {
|
||
|
|
throw new RuntimeException('Service not bound: ' . $id);
|
||
|
|
}
|
||
|
|
|
||
|
|
$this->instances[$id] = ($this->bindings[$id])($this);
|
||
|
|
return $this->instances[$id];
|
||
|
|
}
|
||
|
|
}
|