Skip to content

Instantly share code, notes, and snippets.

@mindplay-dk
Last active February 16, 2022 16:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mindplay-dk/94b647442c2072866e42 to your computer and use it in GitHub Desktop.
Save mindplay-dk/94b647442c2072866e42 to your computer and use it in GitHub Desktop.
Minimal DI container
<?php
class Container
{
/** @var Closure[] */
private $factories = [];
/** @var array */
private $components = [];
public function get($id)
{
if (!isset($this->components[$id])) {
$this->components[$id] = call_user_func($this->factories[$id], $this);
}
return $this->components[$id];
}
public function set($id, $value)
{
$this->components[$id] = $value;
}
public function register($id, Closure $func)
{
$this->factories[$id] = $func;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment