# 1 # S.O.L.I.D Object Oriented Design
In PHP OOP we already know about Dependency Injection, or some design pattern like Factory, singleton. And how about SOLID?
SOLID stands for
Single responsibility principle
Open closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle
# 1 # Single responsibility principle
Single Responsibility Principle or SRP states that every class should have a single responsibility. There should never be more than one reason for a class to change.
Just because you can add everything you want into your class doesn’t mean that you should. Thinking in term of responsibilities will help you design your application better. Ask yourself whether the logic you are introducing should live in this class or not. Using layers in your application helps a lot. Split big classes in smaller ones, and avoid god classes. Last but not least, write straightforward comments. If you start writing comments such as in this case, but if, except when, or, then you are doing it wrong.
// Single Responsibility Principle Violation
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());
}
}
// Refactored
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());
}
}