There are 5 principles in SOLID:
- S – Single Responsibility
- O – Open-Closed
- L – Liskov Substitution
- I – Interface Segregation
- D – Dependency Inversion
This principles makes code clean, extensible and readable. If follow this principle you get architecture that ease to support.
Let’s detail this principles.
Single Responsibility Principle
A class should have one, and only one, reason to change.
It’s very straight forward and easiest one to follow.
The Single Responsibility Principle (SRP) just asks us to do tasks in separate Classes, instead of doing everything at one place (single Class).
Here is the violation of this principle:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Report { public function getTitle() { return 'Report Title'; } public function getDate() { return '2016-04-21'; } public function getContents() { return [ 'title' => $this->getTitle(), 'date' => $this->getDate(), ]; } public function formatJson() { return json_encode($this->getContents()); } } |
Here is refactored code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
class Report { public function getTitle() { return 'Report Title'; } public function getDate() { return '2016-04-21'; } public function getContents() { return [ 'title' => $this->getTitle(), 'date' => $this->getDate(), ]; } } interface ReportFormattable { public function format(Report $report); } class JsonReportFormatter implements ReportFormattable { public function format(Report $report) { return json_encode($report->getContents()); } } |