What is Dependency Injection in CodeIgniter 4?

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.