in solid oop php ~ read.

SOLID - Dependency Inversion Principle

In this post, we are going to talk about the D from SOLID, which is Dependency Inversion Principle.

What is Dependency Inversion Principle.

Normally when we create classes for our software, we will start from the lowest level first. For example if I need to create a Dog class, I will probably define a Animal class first then extend the Dog class from it. This is a bad design since if we want to change the Animal class which means we need to change Dog class as well.

And Dependency Inversion Principle or DIP means that we need to change the dependency of the classes, instead of depending on the concrete class we need to introduce an abstract layer between Dog and Animal class so that the changes of Dog class and Animal class won't interrupt with each other.

Example Code.

Let's have a look at the following example code.

<?php  
// Dependency Inversion Principle - Bad example


class Dog {

    public function walk() {
        // ....walking
    }

}

class Owner {

    $dog;

    public function setDog(Dog $dog) 
    {
        $this->dog = $dog;
    }

    public function walkTheDog() 
    {
        $this->dog->work();
    }
}

class SuperDog {  
    public function walk() 
    {
        //.... walking much more
    }
}

At the first sight you might be thinking oh well it is not that bad. Right cause we don't have too much code here. Let's see the code that follows DIP principle.

<?php  
// Dependency Inversion Principle - Good example

interface IDog {  
    public function work();
}

class Dog implements IDog  
{

    public function walk() {
        // ....walking
    }

}

class SuperDog implements IDog  
{
    public function walk() 
    {
        //.... walking much more
    }
}

class Owner {

    $dog;

    public function setDog(IDog $dog) 
    {
        $this->dog = $dog;
    }

    public function walkTheDog() 
    {
        $this->dog->work();
    }
}

As you can see here, Owner class doesn't not depends on concrete class anymore, instead it depends on a IDog interface which is the middle layer that we mentioned before. Now you are not afraid of changing the Doc or SuperDog class anymore. And also it reduces the coupling between the classes as well.

End

Thanks for reading this post. Hope you guys can learn something from here and apply it to your code. As alwasy if you have any opinions or ideas please leave it below. Thanks!

comments powered by Disqus