# PHP SOLID Principles

SOLID is an acronym for the first five object-oriented design principles by Robert C. Martin. These principles help make software designs more understandable, flexible, and maintainable.

---

## 1. Single Responsibility Principle (SRP)
A class should have only one reason to change. It should have only one job.

```php
// Bad: Handles user data AND email logic
class User {
    public function save() { /* ... */ }
    public function sendEmail() { /* ... */ }
}

// Good: Separate responsibilities
class User {
    public function save() { /* ... */ }
}
class EmailService {
    public function send(User $user) { /* ... */ }
}
```

## 2. Open/Closed Principle (OCP)
Software entities should be open for extension, but closed for modification.

```php
interface Shape {
    public function area();
}

class Rectangle implements Shape {
    public function area() { /* ... */ }
}

class Circle implements Shape {
    public function area() { /* ... */ }
}

// We can add new shapes without modifying the AreaCalculator
class AreaCalculator {
    public function calculate(array $shapes) {
        $area = 0;
        foreach ($shapes as $shape) {
            $area += $shape->area();
        }
        return $area;
    }
}
```

## 3. Liskov Substitution Principle (LSP)
Objects of a superclass shall be replaceable with objects of its subclasses without breaking the application.

If `Bird` is the parent and `Penguin` is the child, `Penguin` should not break code expecting a `Bird`. If `Bird` has a `fly()` method, `Penguin` shouldn't throw an exception when `fly()` is called.

## 4. Interface Segregation Principle (ISP)
Clients should not be forced to depend upon interfaces that they do not use. Split large interfaces into smaller ones.

```php
// Bad
interface Worker {
    public function work();
    public function eat();
}

// Good
interface Workable {
    public function work();
}
interface Feedable {
    public function eat();
}
```

## 5. Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.

```php
interface DBConnectionInterface {
    public function connect();
}

class PasswordReminder {
    private $db;
    public function __construct(DBConnectionInterface $db) {
        $this->db = $db;
    }
}
```

[[programming/php/php]] [[programming/php/php-classes]] [[programming/php/php-design-patterns]]