What is dependency injection container?
A Dependency Injection Container (DIC) is a tool (or system) that automatically manages and provides dependencies (objects) to your classes.
๐ Instead of creating objects manually inside a class, the container creates and injects them for you.
๐ Simple Definition
๐ A Dependency Injection Container is a system that handles object creation and dependency resolution automatically.
๐ First Understand: Dependency Injection (DI)
A dependency is something a class needs to work.
โ Without DI (Tightly Coupled):
class UserService {
private $db; public function __construct() {
$this->db = new Database(); // tightly coupled
}
}
๐ Problem: Hard to test, modify, or replace Database
โ With Dependency Injection:
class UserService {
private $db; public function __construct($db) {
$this->db = $db;
}
}
๐ Now dependency is injected โ flexible ๐
โ๏ธ Role of Dependency Injection Container
Instead of doing this manually:
$db = new Database();
$userService = new UserService($db);
๐ DIC does it automatically ๐ฏ
๐งฉ Simple DIC Example in PHP
class Container {
private $services = []; public function set($name, $callback) {
$this->services[$name] = $callback;
} public function get($name) {
return $this->services[$name]($this);
}
}
๐น Usage
$container = new Container();$container->set('db', function() {
return new Database();
});$container->set('userService', function($c) {
return new UserService($c->get('db'));
});$userService = $container->get('userService');
๐ Benefits of Dependency Injection Container
- ๐ Loose coupling (flexible code)
- ๐งช Easy unit testing (mock dependencies)
- โป๏ธ Reusability
- ๐ง Better code organization
- โก Automatic dependency management
๐ Real-World Usage
Popular PHP frameworks use DIC:
- Laravel โ Service Container
- Symfony โ Dependency Injection Component
๐ก Real-Life Analogy
๐ Think of DIC like a restaurant kitchen ๐ฝ
- You order food (class)
- Kitchen prepares everything (dependencies)
- You just get ready dish
โ ๏ธ Common Mistakes
- โ Overusing container everywhere
- โ Not understanding DI basics
- โ Making container too complex
๐ Best Practices
- Use constructor injection
- Keep services small and focused
- Avoid global/static containers
- Use framework containers when possible
๐ฏ Conclusion
A Dependency Injection Container helps you write clean, maintainable, and scalable code by automatically handling dependencies. It is a must-know concept for modern PHP development and frameworks.
