Courses/PHP/Advanced OOP Patterns

    Lesson 15 โ€ข Advanced

    Advanced OOP Patterns ๐Ÿ—๏ธ

    Master the Factory, Singleton, Strategy, and Repository patterns โ€” the building blocks of professional PHP architecture.

    What You'll Learn in This Lesson

    • โ€ข Singleton: guarantee one instance of a class across your app
    • โ€ข Factory: create objects without hardcoding which class to instantiate
    • โ€ข Strategy: swap algorithms at runtime without changing client code
    • โ€ข Repository: abstract data access behind a clean interface
    • โ€ข When to use (and when NOT to use) each pattern

    Singleton & Factory Patterns

    The Singleton ensures only one instance of a class exists โ€” perfect for database connections and configuration managers. The Factory pattern lets you create objects without specifying their exact class, making your code flexible and extensible. Both are "creational" patterns from the Gang of Four (GoF) book.

    Try It: Singleton & Factory

    See how Singleton shares state and Factory creates different notification types

    Try it Yourself ยป
    JavaScript
    // PHP Design Patterns: Singleton & Factory
    console.log("=== SINGLETON PATTERN ===");
    console.log();
    console.log("Purpose: Ensure a class has only ONE instance globally");
    console.log("Use case: Database connections, config managers, loggers");
    console.log();
    
    // Simulate Singleton in JS
    class Database {
      static instance = null;
      constructor() {
        if (Database.instance) return Database.instance;
        this.connection = "MySQL connection established";
        this.queryCount = 0;
        Database.insta
    ...

    Strategy & Repository Patterns

    The Strategy pattern encapsulates algorithms so you can swap them at runtime โ€” ideal for pricing rules, sorting methods, or validation strategies. The Repository pattern abstracts data access behind an interface, so your business logic doesn't care whether data comes from MySQL, an API, or a file. Both patterns make your code testable and maintainable.

    Try It: Strategy & Repository

    Apply different pricing strategies and use a Repository to manage users

    Try it Yourself ยป
    JavaScript
    // PHP Design Patterns: Strategy & Repository
    console.log("=== STRATEGY PATTERN ===");
    console.log();
    console.log("Purpose: Define a family of algorithms and make them interchangeable");
    console.log("Use case: Sorting, pricing rules, discount calculations");
    console.log();
    
    // Different pricing strategies
    const strategies = {
      regular: (price) => price,
      member: (price) => price * 0.9,
      vip: (price) => price * 0.8,
      bulk: (price, qty) => qty >= 10 ? price * 0.7 : price,
    };
    
    let items = [
      {
    ...

    โš ๏ธ Common Mistakes

    โš ๏ธ
    Overusing Singleton โ€” it introduces global state, which makes testing harder. Prefer dependency injection and only use Singleton for truly shared resources like DB connections.
    โš ๏ธ
    Factory with too many types โ€” if your factory has 20+ branches, consider using a registry or configuration-based approach instead of a giant switch statement.
    โš ๏ธ
    Leaking implementation details โ€” a Repository should never expose SQL queries or database-specific logic. Keep the interface clean and abstract.
    ๐Ÿ’ก
    Pro Tip: Start without patterns. When you notice duplication, tight coupling, or hard-to-test code, THEN apply the appropriate pattern. Premature abstraction is worse than no abstraction.

    ๐Ÿ“‹ Quick Reference โ€” OOP Patterns

    PatternTypeWhen to Use
    SingletonCreationalOne shared instance (DB, config)
    FactoryCreationalCreate objects by type string
    StrategyBehavioralSwap algorithms at runtime
    RepositoryStructuralAbstract data access layer

    ๐ŸŽ‰ Lesson Complete!

    You now know four essential design patterns! Next, learn about Dependency Injection Containers โ€” the key to building testable, decoupled PHP applications.

    Sign up for free to track which lessons you've completed and get learning reminders.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service