What is Dependency Injection in CodeIgniter 4?
Why Interviewers Ask This
This is a differentiating question used for senior and lead roles. Interviewers want to see if you can explain not just what happens, but why — and what the trade-offs are in different approaches.
Answer
CodeIgniter 4 supports Dependency Injection primarily through its Services system and constructor/method injection. Unlike Laravel's fully automatic DI container, CI4 is more explicit. Service injection: inject services through constructor: public function __construct(private UserModel $model, private SessionInterface $session) {} — CI4 will attempt to resolve type-hinted CI4 services automatically. For non-service classes, use the Factories class: Models::UserModel() returns the model singleton. The Services class itself is a simple DI container — register services and their factories there. For true automatic DI (autowiring), CI4 supports it to a limited extent — complex graphs require manual wiring in the Services class. Alternatively, use the CodeIgniter DI container available from the CI4 ecosystem or integrate PHP-DI.
Pro Tip
If you're unsure about a detail, say so honestly and explain your reasoning. Interviewers respect candidates who can think through uncertainty rather than bluffing.
Previous
How does CI4 handle error pages and exceptions?
Next
What is CodeIgniter's Factories class?