Skip to content

Understanding SOLID Principles in PHP

Published: at 09:20 PM

Understanding SOLID Principles in PHP

As a PHP developer, writing clean, maintainable, and scalable code is crucial. The SOLID principles, introduced by Robert C. Martin (Uncle Bob), provide a guideline for designing robust object-oriented systems. In this post, we’ll explore each principle with PHP examples to help you write better code.

1. Single Responsibility Principle (SRP)

A class should have only one reason to change. This means each class should handle only one specific functionality.

Example:

class ReportGenerator {
    public function generateReport($data) {
        // Generate report logic
    }
}

class ReportSaver {
    public function saveReport($report) {
        // Save report logic
    }
}

Here, ReportGenerator handles report creation, while ReportSaver handles storage, ensuring each class has a single responsibility.

2. Open/Closed Principle (OCP)

Software entities should be open for extension but closed for modification. Instead of modifying existing classes, extend them.

Example:

abstract class PaymentProcessor {
    abstract public function pay($amount);
}

class PayPalPayment extends PaymentProcessor {
    public function pay($amount) {
        echo "Processing PayPal payment of $$amount";
    }
}

class StripePayment extends PaymentProcessor {
    public function pay($amount) {
        echo "Processing Stripe payment of $$amount";
    }
}

This allows new payment methods to be added without modifying existing code.

3. Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types. A subclass should extend the base class without altering its expected behavior.

Example:

class Bird {
    public function fly() {
        return "Flying";
    }
}

class Sparrow extends Bird {}

class Penguin extends Bird {
    public function fly() {
        throw new Exception("Penguins cannot fly!");
    }
}

Here, Penguin violates LSP because it alters the expected behavior of Bird. A better approach would be to create separate interfaces for FlyingBird and NonFlyingBird.

4. Interface Segregation Principle (ISP)

Clients should not be forced to depend on interfaces they do not use. Instead of having one large interface, create smaller, specific ones.

Example:

interface Workable {
    public function work();
}

interface Sleepable {
    public function sleep();
}

class HumanWorker implements Workable, Sleepable {
    public function work() {
        echo "Working";
    }
    public function sleep() {
        echo "Sleeping";
    }
}

class RobotWorker implements Workable {
    public function work() {
        echo "Working";
    }
}

Here, RobotWorker does not need a sleep method, adhering to ISP.

5. Dependency Inversion Principle (DIP)

High-level modules should not depend on low-level modules. Both should depend on abstractions.

Example:

interface DatabaseConnection {
    public function connect();
}

class MySQLConnection implements DatabaseConnection {
    public function connect() {
        return "Connected to MySQL";
    }
}

class PostgreSQLConnection implements DatabaseConnection {
    public function connect() {
        return "Connected to PostgreSQL";
    }
}

class UserRepository {
    private $dbConnection;
    
    public function __construct(DatabaseConnection $dbConnection) {
        $this->dbConnection = $dbConnection;
    }
    
    public function getUser() {
        return $this->dbConnection->connect();
    }
}

This allows switching between databases without modifying the UserRepository class.

Conclusion

Applying SOLID principles in PHP helps create code that is maintainable, scalable, and easy to understand. By following these guidelines, you can write better object-oriented PHP applications. Start applying these principles in your projects today!


Previous Post
Laravel Performance Optimization, Best Practices for Faster Applications
Next Post
How to integrate Giscus comments into AstroPaper