🔥 CodeIgniter Intermediate

What is CI4 controller method injection?

Answer

CodeIgniter 4 supports automatic dependency injection in controller methods through type-hinting. When CI4 resolves a controller method, it attempts to resolve type-hinted parameters from the Services class. Inject models: public function index(UserModel $model) — CI4 automatically creates and injects a UserModel instance. Inject services: public function create(ValidationInterface $validation). This reduces the need to call service() or model() manually inside methods. However, CI4's injection is less sophisticated than Laravel's container — it primarily works for CI4 framework classes, not arbitrary user classes. For complex dependency graphs, use the Services class to explicitly configure how classes are built. Constructor injection is more predictable: declare dependencies in __construct() and CI4 resolves them when the controller is instantiated. Method injection is convenient for optional dependencies used in only specific actions.