-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Functions
-
Section 4: Object-Oriented PHP
-
Section 5: Working with Data
-
Section 6: Modern PHP (PHP 8)
-
Section 7: Working with Files and Networking
-
Section 8: Common PHP Frameworks Overview
-
Section 9: Tooling and Ecosystem
-
Section 10: Practical Projects
-
Section 11: Interview Practice
-
Section 12: More Standard Library
-
Section 13: Data Structures and Algorithms in PHP
-
Section 14: More Practice Exercises
-
Section 15: More Security and Best Practices
-
Section 16: More Testing and Tooling
-
Section 17: WordPress-Style CMS Concepts
-
Section 18: Advanced OOP Practice
-
Section 19: More Web Fundamentals
-
Section 20: Database Practice
-
Section 21: PHP Manual: Array Functions
-
Section 22: PHP Manual: Date and Calendar Functions
-
Section 23: PHP Manual: Filesystem and Directory Functions
-
Section 24: PHP Manual: Filter and Var Handling
-
Section 25: PHP Manual: Math Functions
-
Section 26: PHP Manual: JSON and XML
-
Section 27: PHP Manual: Network and Stream Functions
-
Section 28: PHP Manual: Error and Exception Handling
-
Section 29: PHP Manual: Output Control and Misc
-
Section 30: PHP Manual: FTP, Zip, and Mail
-
Section 31: Modern PHP Frameworks Deep Dive
-
Section 32: PHP Design Patterns
-
Section 33: More Practice Exercises
-
Section 34: PHP Performance and Deployment
-
Section 35: More Interview Practice
-
Section 36: More PHP Standard Library
-
Section 37: PHP Concurrency and Async
-
Section 38: More Web Development Practice
-
Section 39: PHP Testing Deep Dive
-
Section 40: Composer and Package Development
-
Section 41: PHP Security Deep Dive
-
Section 42: More Practical Projects
-
Section 43: Legacy PHP Maintenance
-
Section 44: More Algorithm Practice
-
Section 45: Final Practice and Review
-
Section 46: PHP for E-Commerce Patterns
-
Section 47: PHP API Design Deep Dive
-
Section 48: PHP Caching Strategies
-
Section 49: PHP Queue and Background Jobs
-
Section 50: PHP Multi-Tenancy Patterns
-
Section 51: PHP Real-Time Features
-
Section 52: PHP CMS and Content Modeling
-
Section 53: PHP Internationalization
-
Section 54: More Framework-Specific Practice
-
Section 55: PHP Legacy Code Refactoring
-
Section 56: More Practice Projects Round 2
-
Section 57: PHP Command-Line Applications
-
Section 58: PHP and Microservices
-
Section 59: More Interview and Review Round 2
76: Practice Exercise: Building a Simple Dependency Injection Container
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
SmsGatewayclass with a methodsendSms($msg)that returns "SMS Sent: $msg". - Create an
EmailGatewayclass with a methodsendEmail($msg)that returns "Email Sent: $msg". - Create a
NotificationManagerclass that accepts both gateways in its constructor. It should have a methodnotifyAll($msg)that calls both gateways and returns an array of their results. - Instantiate the
Containerand register theSmsGateway,EmailGateway, andNotificationManagerusing the recursive resolution pattern (passing the container$cinto the closure). - Retrieve the
NotificationManagerfrom the container and callnotifyAll("Hello World!")to verify it works.
There are no comments for now.