blog

SOLID Principles (PHP)

Understanding SOLID principles

What is the SOLID-principles?
According to Wikipedia’s definition it’s abbreviation of the five basic principles of design classes in object-oriented design:

Single responsibility
Open-closed
Liskov substitution
Interface segregation
Dependency inversion

1. Single Responsibility

So, as an example lets take popular and widely-used example – an online store with orders, products and customers. The principle states that the only responsibility – “one single duty should be imposed on each object.” In other words – a specific class must solve a specific task – no more and no less. Consider the following description of the class to represent the order in the online store:

Sample 1. Class Order

<?php
class Order
{
    public function calculateTotalSum(){/*...*/}
    public function getItems(){/*...*/}
    public function getItemCount(){/*...*/}
    public function addItem($item){/*...*/}
    public function deleteItem($item){/*...*/}

    public function printOrder(){/*...*/}
    public function showOrder(){/*...*/}

    public function load(){/*...*/}
    public function save(){/*...*/}
    public function update(){/*...*/}
    public function delete(){/*...*/}
}
?>

As you can see, this class performs the operation for 3 different types of tasks: work with every order (calculateTotalSum, getItems, getItemsCount, addItem, deleteItem), display order (printOrder, showOrder) and data handeling (load, save, update, delete).

What does it lead to?

This leads to the case that if we want to make changes to the print job, or storage techniques, we change the order class itself, which may lead to inoperability. To solve this problem is the division of the class into 3 classes, each of which will be to carry out their task:

Sample 2. Class Order split into 3 classes

<?php
class Order
{
    public function calculateTotalSum(){/*...*/}
    public function getItems(){/*...*/}
    public function getItemCount(){/*