First working version with non working routes
This commit is contained in:
54
src/Container/GenericContainer.php
Normal file
54
src/Container/GenericContainer.php
Normal file
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace Ardent\Undercurrent\Container;
|
||||
|
||||
use Exception;
|
||||
|
||||
class GenericContainer
|
||||
{
|
||||
private array $definitions = [];
|
||||
|
||||
private array $instances = [];
|
||||
|
||||
public function add(string $className, ?callable $definition = null, bool $singleton = true): self
|
||||
{
|
||||
if (!$definition) {
|
||||
$definition = function () use ($className) {
|
||||
return new $className();
|
||||
};
|
||||
}
|
||||
|
||||
$this->definitions[$className] = [
|
||||
'definition' => $definition,
|
||||
'singleton' => $singleton,
|
||||
];
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template TClassName
|
||||
* @param class-string<TClassName> $className
|
||||
* @return TClassName
|
||||
* @throws Exception
|
||||
*/
|
||||
public function get(string $className): object
|
||||
{
|
||||
if (!isset($this->definitions[$className])) {
|
||||
throw new Exception("Class $className not found in container");
|
||||
}
|
||||
|
||||
$definition = $this->definitions[$className]['definition'];
|
||||
if ($this->definitions[$className]['singleton']) {
|
||||
if (isset($this->instances[$className])) {
|
||||
return $this->instances[$className];
|
||||
}
|
||||
$instance = $definition();
|
||||
$this->instances[$className] = $instance;
|
||||
} else {
|
||||
$instance = $definition();
|
||||
}
|
||||
|
||||
return $instance;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user