Courses/PHP/Dependency Injection

    Lesson 16 โ€ข Advanced

    Dependency Injection ๐Ÿ’‰

    Build testable, decoupled PHP applications with dependency injection containers and service providers.

    What You'll Learn in This Lesson

    • โ€ข Why tight coupling makes code untestable and fragile
    • โ€ข Constructor, setter, and interface injection techniques
    • โ€ข Build a DI container with bind, singleton, and resolve
    • โ€ข Service providers for organizing registration logic
    • โ€ข The "depend on abstractions, not concretions" principle

    DI Fundamentals: Tight vs Loose Coupling

    Without DI, classes create their own dependencies โ€” hardcoding which database, logger, or mailer to use. This makes swapping implementations impossible and unit testing a nightmare. With DI, dependencies are passed in from outside, so you can inject real services in production and mock objects in tests.

    Try It: DI Basics

    See the difference between tight coupling and dependency injection

    Try it Yourself ยป
    JavaScript
    // Dependency Injection: The Core Concept
    console.log("=== WITHOUT Dependency Injection (Tight Coupling) ===");
    console.log();
    
    class MySQLDatabase {
      connect() { return "Connected to MySQL"; }
      query(sql) { return "MySQL result for: " + sql; }
    }
    
    // โŒ BAD: Class creates its own dependency
    class UserServiceBad {
      constructor() {
        this.db = new MySQLDatabase(); // Hardcoded! Can't swap or test
      }
      getUsers() { return this.db.query("SELECT * FROM users"); }
    }
    
    let bad = new UserServiceBad(
    ...

    Building a DI Container

    A DI container is a registry that knows how to create and wire all your application's services. You register factories (bind) or singletons, and the container resolves the full dependency tree automatically. Frameworks like Laravel, Symfony, and PHP-DI all provide containers โ€” but understanding how they work from scratch makes you a better developer.

    Try It: DI Container

    Build a container with bind, singleton, and resolve โ€” auto-wire services

    Try it Yourself ยป
    JavaScript
    // DI Container: Auto-Wiring Dependencies
    console.log("=== Building a Simple DI Container ===");
    console.log();
    
    class Container {
      constructor() {
        this.bindings = new Map();
        this.singletons = new Map();
      }
    
      // Register a factory function
      bind(name, factory) {
        this.bindings.set(name, { factory, singleton: false });
        console.log("  ๐Ÿ“ฆ Bound: " + name);
      }
    
      // Register as singleton (created once, reused)
      singleton(name, factory) {
        this.bindings.set(name, { factory, si
    ...

    โš ๏ธ Common Mistakes

    โš ๏ธ
    Service Locator anti-pattern โ€” don't pass the container itself into classes. Each class should declare its dependencies explicitly in the constructor, not fetch them from a global container.
    โš ๏ธ
    Injecting too many dependencies โ€” if a class needs 7+ injected services, it's doing too much. Split it into smaller, focused classes with 2-3 dependencies each.
    โš ๏ธ
    Circular dependencies โ€” if A needs B and B needs A, your design is flawed. Extract shared logic into a third class that both can depend on.
    ๐Ÿ’ก
    Pro Tip: In PHP 8+, use constructor promotion to keep DI clean: public function __construct(private readonly UserRepository $users) {}

    ๐Ÿ“‹ Quick Reference โ€” Dependency Injection

    ConceptDescription
    Constructor InjectionPass dependencies via constructor (preferred)
    Setter InjectionPass dependencies via setter methods
    bind()Register a factory โ€” new instance each time
    singleton()Register once โ€” same instance reused
    resolve()Get an instance from the container
    Service ProviderOrganizes bindings into logical groups

    ๐ŸŽ‰ Lesson Complete!

    You can now build decoupled, testable PHP apps with DI! Next, learn advanced error handling with custom exception hierarchies.

    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