Slide 1

Slide 1 text

Dependency Injection 2010/05/25

Slide 2

Slide 2 text

Dependency Injection  For classes with dependencies on other classes.  When an object is used, we pass their dependencies to it.

Slide 3

Slide 3 text

Dependency Injection  When we refer to a class from inside another one, we don't rely care what that class is exactly, only what its interface is. For example: class Car { protected $engine; public function __construct() { $this->engine = new Engine(); } public function go() { $this->engine->on(); $this->engine->applyTorque(); } }

Slide 4

Slide 4 text

Dependency Injection  Engine could be V8Engine, V6Engine, whatever.  So long as we can do the same sort of actions with each, we're set.

Slide 5

Slide 5 text

Dependency Injection  Say we want to test cars with different engines. class RaceTest() { public function testEngines() { $car1 = new Car(); $car2 = new Car(); // Uh ... } } class Car { protected $engine; public function __construct() { $this->engine = new Engine(); } public function go() { $this->engine->on(); $this->engine->applyTorque(); } }

Slide 6

Slide 6 text

Dependency Injection  Let's change Car a bit. class Car { protected $engine; public function __construct(IEngine $engine) { $this->engine = $engine; } public function go() { $this->engine->on(); $this->engine->applyTorque(); } }

Slide 7

Slide 7 text

Dependency Injection  Back to the race. class RaceTest() { public function testEngines() { $car1 = new Car(new V8Engine); $car2 = new Car(new LawnmowerEngine); // calls go() on each in a thread, performs timing tests, // yadda yadda don't care. :-| $test = new SpeedComparison($car1, $car2); return $test->run() ->getResult(); } } class Car { … }

Slide 8

Slide 8 text

So What Do This Give Us?  We're giving Car its dependencies.  Benefit: Flexibility. Dependencies are now based on interfaces, not specific classes.  Benefit: Hey, now it's easier to unit test. ;-) ;-) :-|

Slide 9

Slide 9 text

The Not-So-Good  Drawback: Now you have to give classes what they need.  I'm a programmer, Jim, not a babysitter!  Tentatively suggest using defaults, eg. class Car { protected $engine; public function __construct(IEngine $engine=null) { if (is_null($engine)) { $this->engine = new Engine; } else { $this->engine = $engine; } } }

Slide 10

Slide 10 text

Discussion: Go!