Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active February 25, 2019 13:27
Show Gist options
  • Save Integralist/5763515 to your computer and use it in GitHub Desktop.
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…
<?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();
}
}
}
<?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