Inversion of Control (IoC) is a generic design pattern in which custom-written code receives the flow of control from a generic and reusable class. (free after Wikipedia)

In the example below the custom written code controls the code flow:

class A
{
    public function writeLine($line)
    {
        return sprintf('%s<br />', $line);
    }

}

$a = new A;
echo $a->writeLine('hi');
echo $a->writeLine('my');
echo $a->writeLine('name');
echo $a->writeLine('is');

With the control inverted, the generic class now controls the code flow:

class B
{
    protected $lines = array();

    public function setLine($line)
    {
        $this->lines[] = $line;
    }

    public function getLines()
    {
        return implode("<br />", $this->lines);
    }
}

$b = new B;
$b->setLine('hi');
$b->setLine('my');
$b->setLine('name');
$b->setLine('is');

echo $b->getLines();

Main advantage: separation (decoupling) of implementation and trigger.

This general pattern is implemented in many other patterns, most notably dependency injection (DI) so much so that IoC is often equalled to DI. So-called IoC containers (for example that of Laravel) are actually DI containers. IoC is also called the Hollywood Principle (‘Don’t call us, we call you!’).
Implementations:
* Dependency injection
* Factory pattern
* Observer pattern

Links

* https://en.wikipedia.org/wiki/Inversion_of_control
* http://martinfowler.com/bliki/InversionOfControl.html
* http://www.sitepoint.com/inversion-of-control-the-hollywood-principle/
* http://stackoverflow.com/questions/3058/what-is-inversion-of-control

Advertisements