context.php: add Dependency Injection container implementation

This commit is contained in:
Zankaria 2024-03-12 15:14:35 +01:00 committed by Zankaria
parent d3b94027c4
commit 7dbab7c26c

31
inc/context.php Normal file
View file

@ -0,0 +1,31 @@
<?php
namespace Vichan;
defined('TINYBOARD') or exit;
class Context {
private array $definitions;
public function __construct(array $definitions) {
$this->definitions = $definitions;
}
public function get(string $name): mixed {
if (!isset($this->definitions[$name])) {
throw new \RuntimeException("Could not find a dependency named $name");
}
$ret = $this->definitions[$name];
if (is_callable($ret) && !is_string($ret) && !is_array($ret)) {
$ret = $ret($this);
$this->definitions[$name] = $ret;
}
return $ret;
}
}
function build_context(array $config): Context {
return new Context([
'config' => $config,
]);
}