Dependency Inversion Principle

The dependency inversion principle postulates that classes should not depend on other classes but instead should depend on abstractions. Here is an example of breaking this principle:

<?php
class Switch {
    protected $light;

    public __construct() {
        $this->light = new Light();
    }

    public function turnOn() {
        $this->light->turnOn();
    }

    public function turnOff() {
        $this->light->turnOff();
    }
}

class Light {
    protected $isOn = false;

    public function turnOn() {
        $this->isOn = true;
    }

    public function turnOff() {
        $this->isOn = false;
    }
}

This breaks the dependency inversion principle for several reasons. 1) The constructor has a hard-coded dependency on the Light class. 2) The class depends on a concrete class as opposed to an abstract class.

Details on how to solve this problem can be found in my article on the Abstract Server Pattern

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

About the Author

  • Chris LondonSenior Web ArchitectPartners In Leadership

    I've always worked as an innovative programmer. My insights and creative thinking result in superior products and customer satisfaction. Working full time as a senior web architect I've used lots of exciting technologies (i.e., Ember, Backbone, Handlebars, etc) and developed a lot of exciting sites. In my spare time I hope to develop even more exciting and new technologies. I've been programming professionally for 9 years in everything from desktop applications to web applications to mobile applications.

    Web: https://plus.google.com/116403409191372324375