The post has been translated automatically. Original language: Russian Russian
SOLID is a set of five principles of object-oriented programming (OOP) that help developers write cleaner, more maintainable and flexible code. Let's look at each principle using the PHP example.
S - Single Responsibility Principle: A class should have one responsibility. For example, in PHP, the class responsible for working with the database should not be engaged in data validation.
class UserRepository {
public function save(User $user) {
// The logic of saving the user to the database
}
}
O - Open/Closed Principle: Classes should be open for expansion, but closed for modification. In PHP, this can be implemented using abstract classes and interfaces.
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
// The logic of writing logs to a file
}
}
L - Liskov Substitution Principle: Objects of subclasses should replace objects of the parent class without changing the behavior of the program. For example, if the Bird class has a fly method, then the Penguin subclass should not violate it.
class Bird {
public function fly() {
// Flight logic
}
}
class Penguin extends Bird {
// Penguins do not fly, therefore, the fly method should not exist in Penguin
}
I - Interface Segregation Principle: It is better to have several specialized interfaces than one common one. In PHP, this helps to avoid redundant implementation.
interface Flyable {
public function fly();
}
interface Swimmable {
public function swim();
}
class Duck implements Flyable, Swimmable {
public function fly() {
// Flight logic
}
public function swim() {
// Swimming logic
}
}
D - Dependency Inversion Principle: High-level modules should not depend on low-level modules. Both should depend on abstractions.
interface Mailer {
public function send($recipient, $message);
}
class SmtpMailer implements Mailer {
public function send($recipient, $message) {
// The logic of sending mail via SMTP
}
}
class UserNotification {
private $mailer;
public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}
public function notify($user) {
$this->mailer->send($user->email, "Hello!");
}
}
SOLID principles help to create more structured and maintainable code in PHP, ensuring the stability of the system to changes and improving its scalability.
SOLID — это набор из пяти принципов объектно-ориентированного программирования (ООП), которые помогают разработчикам писать более чистый, поддерживаемый и гибкий код. Рассмотрим каждый принцип на примере PHP.
S - Single Responsibility Principle (Принцип единственной ответственности): Класс должен иметь одну ответственность. Например, в PHP класс, отвечающий за работу с базой данных, не должен заниматься валидацией данных.
class UserRepository {
public function save(User $user) {
// Логика сохранения пользователя в базу данных
}
}
O - Open/Closed Principle (Принцип открытости/закрытости): Классы должны быть открыты для расширения, но закрыты для изменения. В PHP это можно реализовать с помощью абстрактных классов и интерфейсов.
interface Logger {
public function log($message);
}
class FileLogger implements Logger {
public function log($message) {
// Логика записи логов в файл
}
}
L - Liskov Substitution Principle (Принцип подстановки Лисков): Объекты подклассов должны заменять объекты родительского класса без изменения поведения программы. Например, если класс Bird имеет метод fly, то подкласс Penguin не должен его нарушать.
class Bird {
public function fly() {
// Логика полета
}
}
class Penguin extends Bird {
// Пингвины не летают, следовательно, метод fly не должен существовать в Penguin
}
I - Interface Segregation Principle (Принцип разделения интерфейса): Лучше иметь несколько специализированных интерфейсов, чем один общий. В PHP это помогает избежать избыточной реализации.
interface Flyable {
public function fly();
}
interface Swimmable {
public function swim();
}
class Duck implements Flyable, Swimmable {
public function fly() {
// Логика полета
}
public function swim() {
// Логика плавания
}
}
D - Dependency Inversion Principle (Принцип инверсии зависимостей): Модули высокого уровня не должны зависеть от модулей низкого уровня. Оба должны зависеть от абстракций.
interface Mailer {
public function send($recipient, $message);
}
class SmtpMailer implements Mailer {
public function send($recipient, $message) {
// Логика отправки почты через SMTP
}
}
class UserNotification {
private $mailer;
public function __construct(Mailer $mailer) {
$this->mailer = $mailer;
}
public function notify($user) {
$this->mailer->send($user->email, "Hello!");
}
}
Принципы SOLID помогают создавать более структурированный и поддерживаемый код в PHP, обеспечивая устойчивость системы к изменениям и улучшая её масштабируемость.