Advertisement
Intermediate PHP, Dependency Injection & Service Containers

How does autowiring work in a service container, and how does it use type hints to automatically resolve a class's dependencies?

Short answer

Autowiring is a service container feature that inspects a class's constructor type hints using PHP's reflection capabilities, automatically determining what dependencies that class needs and recursively resolving and constructing each of those dependencies as well, meaning…

Save PHP mock interview
Advertisement
AModel answer
Autowiring is a service container feature that inspects a class's constructor type hints using PHP's reflection capabilities, automatically determining what dependencies that class needs and recursively resolving and constructing each of those dependencies as well, meaning developers often do not need to manually configure how most classes should be built at all, since the container can figure it out automatically as long as the dependencies are properly type hinted.
class ReportService {
    public function __construct(private Database $db, private Logger $logger) {}
}
$report = $container->make(ReportService::class);
// Container automatically resolves Database and Logger
Real-world example
A developer adds a new dependency to a class's constructor and the framework's service container automatically figures out how to construct and inject it without requiring any additional manual configuration, simply based on the newly added type hint.
Likely follow-ups
  • What happens if a class depends on an interface rather than a concrete class during autowiring?
  • Are there performance costs associated with autowiring using reflection?
Related topics