Files
breadcrumb-the-shire/lib/App/AppContainer.php

39 lines
912 B
PHP
Raw Normal View History

2026-03-04 15:56:58 +01:00
<?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];
}
}