Skip to Content
Course content

76: Practice Exercise: Building a Simple Dependency Injection Container

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Listen, we've spent a few lessons talking about the *concept* of Dependency Injection, but it often feels like a theoretical architectural pattern until you actually have to wire a large application together. Doing it manually in a bootstrap file is fine for three classes, but it becomes a nightmare when you have fifty. That's where a Dependency Injection Container (DIC) comes in.

Instead of us manually instantiating every dependency, we're going to build a tiny container that knows how to "resolve" classes. I want to keep this simple: a class that stores "recipes" for how to create objects and then serves them up when we ask for them.

Setting up our dependencies

To make this concrete, let's imagine we're building a user registration system. We'll need a Database connection, a Logger to track errors, and a UserService that relies on both of them. I'll keep these classes lean so we can focus on the container.

class Database {
    public function query($sql) {
        return "Executing: $sql";
    }
}

class Logger {
    public function log($message) {
        echo "[LOG]: $message\n";
    }
}

class UserService {
    public function __construct(
        private Database $db,
        private Logger $logger
    ) {}

    public function createUser($name) {
        $this->logger->log("Creating user $name");
        return $this->db->query("INSERT INTO users VALUES ('$name')");
    }
}

The basic container structure

Now, the container itself. I want a way to set a definition (a "recipe") and a way to get the resulting object. I'll use an associative array to store closures. Closures are perfect here because they allow us to defer the actual instantiation until the moment the service is actually needed—what we call "lazy loading."

class Container {
    private array $services = [];
    private array $instances = [];

    public function set(string $name, callable $definition): void {
        $this->services[$name] = $definition;
    }

    public function get(string $name) {
        if (!isset($this->services[$name])) {
            throw new Exception("Service $name not found in container.");
        }

        // If we already created this service, just return it (Singleton pattern)
        if (isset($this->instances[$name])) {
            return $this->instances[$name];
        }

        $definition = $this->services[$name];
        $this->instances[$name] = $definition();
        return $this->instances[$name];
    }
}

Correcting a major oversight

Here is where I usually trip up when first sketching this out. If I try to use the container now, look at how I have to define my services:

$container = new Container();
$container->set('db', fn() => new Database());
$container->set('logger', fn() => new Logger());
$container->set('user_service', fn() => new UserService(new Database(), new Logger()));

Wait. I've just defeated the whole purpose. In the user_service definition, I'm manually calling new Database() and new Logger() again. If the Database class ever requires a configuration object in its constructor, I'll have to hunt down every single place I manually instantiated it across my entire container config. That's a maintenance disaster.

The container needs to be able to resolve its own dependencies. I need to pass the container instance itself into the closure so the closure can ask the container for the other required services.

Here is the fix. I'll modify the get method to pass $this into the callable:

// Inside the Container class...
public function get(string $name) {
    if (!isset($this->services[$name])) {
        throw new Exception("Service $name not found.");
    }

    if (isset($this->instances[$name])) {
        return $this->instances[$name];
    }

    $definition = $this->services[$name];
    
    // NOTICE: I'm passing $this (the container) into the closure
    $this->instances[$name] = $definition($this); 
    
    return $this->instances[$name];
}

Now, my service definitions become much cleaner and truly decoupled:

$container = new Container();

$container->set('db', fn() => new Database());
$container->set('logger', fn() => new Logger());

// Now the UserService asks the container for its dependencies
$container->set('user_service', function($c) {
    return new UserService($c->get('db'), $c->get('logger'));
});

$userService = $container->get('user_service');
echo $userService->createUser('Alice');

This is the "magic" of a DI container. The UserService doesn't know where the Database comes from; it just knows it needs one. The container handles the graph of dependencies, ensuring that every object is created in the right order and only once.




📋 Practical Task

Exercise: Extending the Container for a Notification System

You need to implement a notification system using the Container class built in the lesson. Your goal is to wire together a system where a NotificationManager depends on a SmsGateway and an EmailGateway.

Requirements:

  • Create an SmsGateway class with a method sendSms($msg) that returns "SMS Sent: $msg".
  • Create an EmailGateway class with a method sendEmail($msg) that returns "Email Sent: $msg".
  • Create a NotificationManager class that accepts both gateways in its constructor. It should have a method notifyAll($msg) that calls both gateways and returns an array of their results.
  • Instantiate the Container and register the SmsGateway, EmailGateway, and NotificationManager using the recursive resolution pattern (passing the container $c into the closure).
  • Retrieve the NotificationManager from the container and call notifyAll("Hello World!") to verify it works.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.