Skip to content

Instantly share code, notes, and snippets.

@niallobrien
Last active December 17, 2015 20:39
Show Gist options
  • Save niallobrien/5669430 to your computer and use it in GitHub Desktop.
Save niallobrien/5669430 to your computer and use it in GitHub Desktop.
PHP simple IoC example
<?php
class Container
{
protected $registry = [];
// Typehint Closure to show expected object
public function bind($name, Closure $closure)
{
// Populate $registry array with passed-in $closure
$registry[$name] = $closure;
}
// Pass in the array key which corresponds to a closure in this case (can return object instances etc. too)
public function make($name)
{
if (isset($registry[$name])) {
return $registry[$name]();
}
}
}
// Implementation example
<?php
// Create a new container object
$container = new Container;
// The bind() method on Container expects to be passed a key/name for the array and a closure.
// Bind the closure (new Cat object).
$container->bind('cat', function() {
// return a new instance of a Cat object (class not provided in this example) after
// passing in an array with the cat's temper attribute (string, associative array, whatever).
return new Cat('Angry Cat');
});
// Pass 'cat' as the key/name into make() to resolve the object from the container.
$cat = $container->make('cat');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment