Last active
February 25, 2019 13:27
-
-
Save Integralist/5763515 to your computer and use it in GitHub Desktop.
S.O.L.I.D - (D)ependency Inversion. In the bad example, yes we're injecting our dependency but the Button class is now no longer reusable as it is too tightly coupled to the Lamp class. In the better example, we're still injecting our dependency but we now inverse the control via the use of an Interface. So now any `SwitchableDevice` can be used…
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 Lamp | |
{ | |
public function turnOn() | |
{ | |
// code | |
} | |
public function turnOff() | |
{ | |
// code | |
} | |
} | |
class Button | |
{ | |
private $lamp; | |
public function __construct(Lamp $lamp) | |
{ | |
$this->lamp = $lamp; | |
} | |
public function doSomething() | |
{ | |
if (x) { | |
$this->lamp->turnOn(); | |
} | |
} | |
} |
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 SwitchableDevice | |
{ | |
public function turnOn(); | |
public function turnOff(); | |
} | |
class Lamp implements SwitchableDevice | |
{ | |
public function turnOn() | |
{ | |
// code | |
} | |
public function turnOff() | |
{ | |
// code | |
} | |
} | |
class Button | |
{ | |
private $switchableDevice; | |
public function __construct(SwitchableDevice $switchableDevice) | |
{ | |
$this->switchableDevice = $switchableDevice; | |
} | |
public function doSomething() | |
{ | |
if (x) { | |
$this->switchableDevice->turnOn(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment