📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Dependency Injection

Dependency Injection

6 min read Quiz at the end
Dependency Injection passes required objects to a class through the constructor instead of creating them internally. This makes classes easier to test and swap. Type-hint against interfaces for maximum flexibility.

Dependency Injection

// Without DI — tightly coupled, hard to test
class UserService {
    public function find(int $id): array {
        $pdo = new PDO("mysql:...", "user", "pass"); // hardcoded!
        // ...
    }
}

// With DI — decoupled, easy to test and swap
class UserService {
    public function __construct(
        private UserRepository $repo,
        private LoggerInterface $logger,
        private CacheInterface $cache
    ) {}

    public function find(int $id): ?User {
        $this->logger->info("Finding user $id");

        return $this->cache->remember("user.$id", 3600,
            fn() => $this->repo->findById($id)
        );
    }
}

// DI Container (basic)
$container = new Container();
$container->bind(LoggerInterface::class, FileLogger::class);
$service = $container->make(UserService::class);
Topic Quiz · 5 questions

Test your understanding before moving on

1. What problem does Dependency Injection solve?
💡 DI decouples components by injecting dependencies rather than creating them internally.
2. What is a DI Container?
💡 A DI Container automatically resolves and injects class dependencies.
3. Constructor injection means:
💡 Constructor injection passes dependencies as constructor parameters — the preferred method.
4. Which design principle does DI implement?
💡 DI implements the Dependency Inversion Principle — depend on abstractions, not concretions.
5. What makes code using DI easier to test?
💡 With DI, you can replace real services with test doubles (mocks/stubs) during testing.