SOLID Principle with Examples in PHP
--
In Object-Oriented Programming (OOP), we rely on the concept of objects/classes where everything inside of it is an object. It’s kind of useful because it’s similar to the way we live where everything is an object. With the OOP paradigm, our codes will be much easier to maintain, understand, and tends to be reusable.
When working in OOP, we’ll usually follow the S.O.L.I.D principle. The principle working greatly with the OOP programming because it’ll make our codes better in every way, and we can maximize the potential of OOP. So in this article, I’ll show you all of these principles as well as the practical example of using them in PHP Languages.
Before we start, let me explain what we’re going to build using the SOLID principle. We’re going to create a simple message responder where when we input a text, it’ll return a message/string based on the text we inputted. It’s so basic that we can even use if-else or switch statements to do that, but we’ll refactor it later by using the SOLID principles and let’s see the improvements we can make from it.
Content Overview
- Single-Responsibility Principle
- Open-closed Principle
- Liskov Substitution Principle
- Interface Segregation Principle
- Dependency Inversion Principle
#1 Single-Responsibility Principle
The first principle, SRP states:
There should never be more than one reason for a class to change. In other words, every class should have only one responsibility. — objectmentor.com (pdf)
Well, if we take a look at our codes above, it’s violating the first principle here, because the class we created responsible for everything. From receiving the user message, then maybe we need to do something with the given message, then return a response. So…