Single Responsibility Principle

"There are two parts to learning craftsmanship: knowledge and work." - Robert C. Martin

Single Responsibility Principle

Zasada pojedynczej odpowiedzialności single responsibility principle

The single responsibility principle is that each class should be responsible for one particular thing. This means more or less that there should not be more than one reason to modify a given class. The application of this principle in the code significantly increases the number of classes in the program. Many small classes are created with one functionality, while the number of very complex, multifunctional classes is reduced. Defining a sufficient number of interfaces considerably increases the flexibility of the code in the future. The figure below shows the source code breaking the SRP rule.

 
class Registration 
{ 
private $login; 
private $password;
 
public function __construct($login, $password) 
{ 
$this->login = $login; 
$this->password = $password; 
} 

public function validateLogin() 
{ 
echo 'Login validation'; 
} 

public function saveUserToDatabase() 
{ 
echo '<span id="result_box" class="short_text" lang="en" tabindex="-1"><span class="">Saving a new user to the database</span></span>'; 
} 
}
$user = new Registration('user123','myPassword123'); 
$user->validateLogin(); 
$user->saveUserToDatabase(); 

The Registration class is responsible for two things, checks whether the login provided by the user is already in the database and saves the data of the new user to the database. As according to the SRP rule, the class should have one responsibility, the Registration class should be divided into two smaller classes – Registration class, which saveUserToDatabase() method saves the new user to the database and loginValidator class, whose validateLogin() method checks if the given login is already in the database. Correctly divided classes are presented in the following PHP source code.

 
class Registration 
{ 
private $login; 
private $password; 

public function __construct($login, $password) 
{ 
$this->login = $login; 
$this->password = $password; 
} 

public function saveUserToDatabase() 
{ 
echo '<span id="result_box" class="short_text" lang="en" tabindex="-1"><span class="">Saving a new user to the database</span></span>'; 
} 
} 

class LoginValidator 
{ 
public function __construct($login) 
{ 
$this->login = $login; 
}
 
public function validateLogin() 
{ 
echo 'Login validation'; 
} 
}

$user = new Registration('user123','myPassword123'); 
$user = new LoginValidator('user123'); 
$user-> validateLogin(); 
$user-> saveUserToDatabase();