Skip to content

Instantly share code, notes, and snippets.

@stwalkerster
Created January 31, 2016 03:55
Show Gist options
  • Save stwalkerster/1aa49a879ccdaaa90470 to your computer and use it in GitHub Desktop.
Save stwalkerster/1aa49a879ccdaaa90470 to your computer and use it in GitHub Desktop.
dependency injection primer
<?php
class PetrolEngine {
public function vroom() {}
}
class Car {
private $engine = new PetrolEngine();
public function goFaster() {
$engine->vroom();
}
}
$myCar = new Car();
$myCar->goFaster();
<?php
interface Engine {
public function vroom();
}
class PetrolEngine implements Engine{
public function vroom() {}
public function addPetrol() {}
}
class DieselEngine implements Engine{
public function vroom() {}
public function addDiesel() {}
}
class Car {
private $engine;
public function __construct(Engine $engine) {
$this->engine = $engine;
}
public function goFaster() {
$engine->vroom();
}
}
$myEngine = new PetrolEngine();
$myCar = new Car($myEngine);
$myCar->goFaster();
$myOtherEngine = new DieselEngine();
$myOtherCar = new Car($myOtherEngine);
$myCar->goFaster();
<?php
class PetrolEngine {
public function vroom() {}
}
class Car {
private $engine;
public function __construct($engine) {
$this->engine = $engine;
}
public function goFaster() {
$engine->vroom();
}
}
$myEngine = new PetrolEngine();
$myCar = new Car($myEngine);
$myCar->goFaster();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment