Created
January 31, 2016 03:55
-
-
Save stwalkerster/1aa49a879ccdaaa90470 to your computer and use it in GitHub Desktop.
dependency injection primer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class PetrolEngine { | |
public function vroom() {} | |
} | |
class Car { | |
private $engine = new PetrolEngine(); | |
public function goFaster() { | |
$engine->vroom(); | |
} | |
} | |
$myCar = new Car(); | |
$myCar->goFaster(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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