40 lines
1.0 KiB
PHP
40 lines
1.0 KiB
PHP
<?php
|
|
namespace Blog\Core;
|
|
|
|
use Exception;
|
|
|
|
/**
|
|
* Ein einfacher Dependency Injection Container.
|
|
*/
|
|
class Container {
|
|
/**
|
|
* @var array Liste der registrierten Instanzen.
|
|
*/
|
|
private array $instances = [];
|
|
|
|
/**
|
|
* Registriert eine Instanz oder Factory-Funktion im Container.
|
|
*
|
|
* @param string $key Der eindeutige Schlüssel für die Instanz.
|
|
* @param callable $factory Eine Factory-Funktion, die eine Instanz erzeugt.
|
|
* @return void
|
|
*/
|
|
public function set(string $key, callable $factory): void {
|
|
$this->instances[$key] = $factory;
|
|
}
|
|
|
|
/**
|
|
* Ruft eine registrierte Instanz ab und erstellt sie falls nötig.
|
|
*
|
|
* @param string $key Der Schlüssel der angeforderten Instanz.
|
|
* @return mixed Die abgerufene Instanz.
|
|
* @throws Exception Wenn keine Instanz mit dem gegebenen Schlüssel existiert.
|
|
*/
|
|
public function get(string $key): mixed {
|
|
if(!isset($this->instances[$key])) {
|
|
throw new Exception("No instance found for {$key}");
|
|
}
|
|
return $this->instances[$key]($this);
|
|
}
|
|
}
|