Last active
August 16, 2021 14:45
-
-
Save kobus1998/679d2f6e6213c1a5b29377356cdf7045 to your computer and use it in GitHub Desktop.
minimal di-container
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Container { | |
public $config; | |
public $cache = []; | |
public function __construct($config) | |
{ | |
$this->config = $config; | |
$this->checkConflicts($config); | |
} | |
protected function checkAgainst($class, $params) | |
{ | |
if (is_array($params)) { | |
foreach ($params as $check) { | |
if ($check === $class) { | |
throw new LogicException("conflicts in the config for {$class}"); | |
} | |
if (isset($this->config[$check])) { | |
$this->checkAgainst($class, $this->config[$check]); | |
} | |
} | |
} | |
} | |
public function checkConflicts($config) | |
{ | |
foreach ($config as $class => $params) { | |
$this->checkAgainst($class, $params); | |
} | |
} | |
public function get($class) | |
{ | |
if (isset($this->cache[$class])) { // cached | |
return $this->cache[$class]; | |
} | |
if (!isset($this->config[$class])) { | |
throw new InvalidArgumentException("{$class} does not exists in config"); | |
} | |
$aParams = []; | |
foreach ($this->config[$class] as $param) { | |
if (is_string($param) && class_exists($param)) { | |
if ($param === $class) { | |
throw new LogicException("you can't require the same class as parameter"); | |
} | |
$aParams[] = $this->get($param); | |
continue; | |
} | |
$aParams[] = $param; | |
} | |
$this->cache[$class] = new $class(...$aParams); | |
return $this->cache[$class]; | |
} | |
public function has($class) | |
{ | |
return isset($this->config[$class]); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$container = new Container([ // config, key value: class => parameters[] | |
FooBar::class => [], | |
Bar::class => [FooBar::class], | |
Foo::class => [Bar::class] | |
]); | |
$foo = $container->get(Foo::class); // Foo | |
echo get_class($foo->bar) // Bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment