Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Dependency Injection (2010)

Dependency Injection (2010)

The fourth in a short series of presentations given at a PHP development shop.

Rob Howard

May 25, 2010
Tweet

More Decks by Rob Howard

Other Decks in Technology

Transcript

  1. Dependency Injection  For classes with dependencies on other classes.

     When an object is used, we pass their dependencies to it.
  2. 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(); } }
  3. Dependency Injection  Engine could be V8Engine, V6Engine, whatever. 

    So long as we can do the same sort of actions with each, we're set.
  4. 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(); } }
  5. 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(); } }
  6. 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 { … }
  7. 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. ;-) ;-) :-|
  8. 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; } } }