The Solid Design Principle — Single Responsibility
In this series, we’re going to discuss the five Solid Principle, this is actually applied to all Object-Oriented Programming, not just PHP
The five solid designs are listed below
S — Single Responsibility
O — Open/Close
L — Liskov Substitution
I — Interface Segregation
D — Dependency Inversion
So in this write up I will be writing about the S
S — Single Responsibility
This state that a class should have only one reason to change, in simpler terms, a class should only have one task or one responsibility so if there are any other methods in a class that deals with something completely different, that method should be extracted and put somewhere else and your class should have one task/job/responsibilities
Why The Need For Single Responsibility
if we keep our classes just with one responsibility, it does the following
Makes the class easier to maintain.
Potentially make class reusable ( depending on whatever your class is dealing with)
-
Easier to test
Now the above class breaks the single responsibility principle because it has more than one responsibility or task, and the reason for this is because of the method logError. Create and Edit Method has perfect reasons to stay in the User Class, it actually performs actions upon the User but the logError does otherwise
So how do we fix this?
We can extract the logError method and keep it in its own class,
*<?php
class *Logger {
*public function *writeToFile($message){
*//Write To File
*}
}
we can also have flexible and expandable enough for it to save to file or save to external resource so if we still need the LogError method then use dependency injection to inject it into the User Class
Thanks for reading, I hope this clears any questions on responsibility principle, if you have any question, simply drop a comment below
Top comments (0)