« Back to Index

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 with the Button class.

View original Gist on GitHub

1. Bad Example.php

<?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();
        }
    }
}

2. Better Example.php

<?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();
        }
    }
}