niallobrien
5/29/2013 - 10:43 AM

PHP simple IoC example

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');