What is CI4 controller method injection?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a CodeIgniter codebase.
Previous
What is the difference between CI4 redirect()->to() and redirect()->back()?
Next
What is CI4 response download?