Skip to main content

Lesson 5 of 7

SOLID Principles in PHP

SOLID is five object-oriented design principles that produce maintainable, extensible, testable code. They are not PHP-specific - but PHP's OOP features map cleanly to each principle. Understanding SOLID is what separates junior developers from those who write code that survives real-world projects.

18 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

All 5 SOLID Principles with PHP Examples

All 5 SOLID Principles with PHP Examples
<?php
declare(strict_types=1);

// ── S - Single Responsibility Principle ───────────────────────
// A class should have ONE reason to change.

// ❌ Violates SRP - does too many things
class PostManager {
    public function savePost(array $data): void { /* DB */ }
    public function sendNotification(string $email): void { /* Email */ }
    public function generateSlug(string $title): string { /* string op */ }
    public function renderPost(array $post): string { /* HTML */ }
}

// ✅ SRP - each class has one job
class PostRepository  { public function save(Post $post): Post { /* DB */ return $post; } }
class EmailNotifier   { public function notify(string $email): void { /* Email */ } }
class SlugGenerator   { public function generate(string $title): string { return strtolower($title); } }
class PostService     { /* orchestrates the above - coordination is its job */ }

// ── O - Open/Closed Principle ─────────────────────────────────
// Open for extension, closed for modification.

// ❌ Adding new payment types requires modifying processPayment
class PaymentProcessor {
    public function process(string $type, float $amount): bool {
        if ($type === "stripe") { /* stripe logic */ }
        elseif ($type === "paypal") { /* paypal logic */ }
        return true;
    }
}

// ✅ OCP - new methods: add a class, change nothing
interface PaymentGatewayInterface {
    public function charge(float $amount): bool;
    public function refund(float $amount): bool;
}
class StripeGateway  implements PaymentGatewayInterface { public function charge(float $a): bool { return true; } public function refund(float $a): bool { return true; } }
class PayPalGateway  implements PaymentGatewayInterface { public function charge(float $a): bool { return true; } public function refund(float $a): bool { return true; } }
class CryptoGateway  implements PaymentGatewayInterface { public function charge(float $a): bool { return true; } public function refund(float $a): bool { return true; } }

class PaymentService {
    public function __construct(private PaymentGatewayInterface $gateway) {}
    public function pay(float $amount): bool { return $this->gateway->charge($amount); }
}
// Adding Bitcoin? new CryptoGateway - PaymentService unchanged.

// ── L - Liskov Substitution Principle ─────────────────────────
// Subclasses must be substitutable for their base class.

// ❌ Violates LSP - square breaks rectangle's invariant
class Rectangle {
    protected int $width;
    protected int $height;
    public function setWidth(int $w): void  { $this->width = $w; }
    public function setHeight(int $h): void { $this->height = $h; }
    public function area(): int { return $this->width * $this->height; }
}
class Square extends Rectangle {
    public function setWidth(int $w): void  { $this->width = $this->height = $w; } // breaks contract!
    public function setHeight(int $h): void { $this->height = $this->width = $h; }
}

// ✅ LSP - any PostRepositoryInterface implementation is substitutable
interface PostRepositoryInterface2 {
    public function findById(int $id): ?Post;
}
// PdoPostRepository, InMemoryPostRepository both honour the contract
// PostService works correctly with either - that's LSP

// ── I - Interface Segregation Principle ──────────────────────
// Don't force classes to implement methods they don't need.

// ❌ ISP violation - read-only repo forced to implement write methods
interface CrudRepositoryInterface {
    public function findById(int $id): ?Post;
    public function save(Post $post): Post;
    public function delete(int $id): bool;
}

// ✅ ISP - segregated interfaces
interface ReadRepositoryInterface {
    public function findById(int $id): ?Post;
    public function findAll(): array;
}
interface WriteRepositoryInterface {
    public function save(Post $post): Post;
    public function delete(int $id): bool;
}
// Read-only repo: implements only ReadRepositoryInterface
// Full repo: implements both

// ── D - Dependency Inversion Principle ───────────────────────
// Depend on abstractions, not concretions.

// ❌ DIP violation - hard-coded dependency
class PostServiceBad {
    private PdoPostRepository $repo;
    public function __construct(PDO $pdo) {
        $this->repo = new PdoPostRepository($pdo);  // concrete! untestable
    }
}

// ✅ DIP - inject the abstraction
class PostServiceGood {
    public function __construct(
        private readonly PostRepositoryInterface $repo,  // abstraction
        private readonly EmailNotifier          $notifier,
    ) {}

    public function publishPost(int $id): Post {
        $post = $this->repo->findById($id);
        if ($post === null) throw new PostNotFoundException($id);
        $published = $post->publish();
        $this->repo->save($published);
        return $published;
    }
}

Quick Quiz

Tip

Tip

Practice SOLID Principles in PHP in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

Visual architecture and concepts for SOLID Principles in PHP

Practice Task

Note

Practice Task - (1) Write a working example of SOLID Principles in PHP from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Common Mistake

Warning

A common mistake with SOLID Principles in PHP is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/7 done