Skip to content

Instantly share code, notes, and snippets.

@stwalkerster
Created Jan 31, 2016
Embed
What would you like to do?
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