Single Responsibility Principle(SRP) example using PHP.

Do you want to know why it’s good for a class to have one and only one reason to change? if yes this short and well-articulated article will use a real-world example to explain one of the object-oriented design principles by Robert C. Martin.

Omo Junior
3 min readMar 6, 2023
unknown source

Before we go ahead with the mean topic of this article, we will first look at the SOLID acronym.

SOLID is an acronym for the first five object-oriented design principles by Robert C. Martin.
These five principles consist of practices that lead to developing software with considerations of scalability and maintenance.

SOLID stands for :
S. Single—Responsibility Principle
O. Open-Closed Principle
L.Liskov Substitution Principle
I. Interface Segregation Principle
D.Dependency Inversion Principle

In this article, we will be looking at one of the five object-oriented design principles (SRP).

What is the Single Responsibility Principle?

The SRP is an object-oriented programming principle that states that a class should have only one reason to change. Meaning a class should have one responsibility and not two or more.

This makes the code maintainable, extensible, and easier to understand by others working on the project or codebase.

Example of what is not SRP :

By Author

The example above violates SRP, as you can see the User class has multiple responsibilities such as validation, registration, login, and password reset.
Imagine if we are to add a new feature to this class, that would lead to modification which SRP is against.

Example of what SRP should look like:

By Author
By Author

In the examples above we have separated the responsibilities into different classes. This satisfies the Single Responsibility Principle.

This simple and short example of how SRP can be significant for better development should not just be limited to bigger projects, try to make use of this principle even in smaller projects because the better and cleaner the codebase looks the simpler maintainability becomes.

Hope you were able to find this article helpful, as humans we are not error-free with that said if you think something should have been added or removed kindly share your thoughts as a response.

--

--

Omo Junior

Full-Stack Developer, Co.Founder @Omomakay Liberia, UI/UX Designer