Skip to content

Instantly share code, notes, and snippets.

@niallobrien
Last active Dec 17, 2015
Embed
What would you like to do?
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