IoC container in Laravel 3

The IoC container in Laravel is a hidden diamond in the rough that not a lot of people seem to know about. It allows for dependency injection and extremely testable code. However, there was a bug in it so that you could not resolve any class that used optional parameters in it’s constructors (including Eloquent). The bug had been fixed in Laravel 4 which is still not out for beta, so I decided to backport this to Laravel 3 for Taylor (since he’s really busy with L4).

I also snuck in some extra functionality. The ability to pass in parameters to the resolve. This allows us to override the resolve if we need to do so which is a nice feature when using a lot of nested DI (especially if you’re componsating for testing doubles). See below

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Foo
{
public $bar;
public __construct(Bar bar)
{
$this->bar = bar;
}
}

class Bar
{
public $neato = "hmm";
}

$bar1 = IoC::resolve('Bar');
$bar1->neato = "Something else";
$foo1 = IoC::resolve('Foo', [$bar1]);
$foo2 = IoC::resolve('Foo');

// you can control your bars man!
print $foo1->bar->neato . ' ' .
$foo2->bar->neato;