Skip to content

Instantly share code, notes, and snippets.

@slogsdon
Created July 8, 2015 18:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slogsdon/975208210cdefc0fb5df to your computer and use it in GitHub Desktop.
Save slogsdon/975208210cdefc0fb5df to your computer and use it in GitHub Desktop.
Basic dependency injection container for PHP
<?php
class ServiceContainer
{
private static $services;
private static $generators;
public function __construct()
{
self::$services = [];
self::$generators = [];
}
public function register($name, $generator)
{
self::$generators[$name] = $generator;
return $this;
}
public function get($name)
{
if (!isset(self::$generators[$name])) {
throw new ServiceNotDefinedException($name);
}
if (!isset(self::$services[$name])) {
self::$services[$name] = call_user_func(self::$generators[$name], $this);
}
$service = self::$services[$name];
return is_callable($service)
? call_user_func($service, $this)
: $service;
}
public function value($value)
{
return function ($s) use ($value) {
return $value;
};
}
public function factory($factory)
{
return function ($s) use ($factory) {
return call_user_func($factory, $s);
};
}
}
<?php
class ServiceNotDefinedException extends Exception
{
public function __construct($name)
{
$message = sprintf('Service "%s" is not defined', $name);
parent::__construct($message);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment