Model Dependency Injection in CodeIgniter Controller - How to Achieve It? |
Hello,
I'm seeking guidance on how to perform model dependency injection into a CodeIgniter Controller's constructor. Does CodeIgniter have built-in support for this, or are there any recommended practices to achieve model dependency injection? If CodeIgniter doesn't natively support model dependency injection in Controllers, what alternative approaches would you suggest to accomplish this? I appreciate any insights or examples you can share! Thank you.
There is no DI container. Autowire is also not.
You need to install dependencies directly in the method or constructor (new Class or factories). There is a global analog of the Config\Services container
If you really need Dependency Injection, you can install a DI container, and create controllers by the container.
In this case, you need to extend the CodeIgniter class. See - https://github.com/kenjis/ci4-tettei-app...gniter.php - https://github.com/kenjis/ci4-tettei-app...rvices.php (08-09-2023, 09:14 AM)tarcisiodev1 Wrote: If CodeIgniter doesn't natively support model dependency injection in Controllers, what alternative approaches would you suggest to accomplish this? CodeIgniter provides `model()` function. It is a wrapper function for the service locator "Factories". It instantiates an model and share it. See https://codeigniter4.github.io/CodeIgnit...ing-models It is not dependency injection, but dependency pull.
(08-09-2023, 05:37 PM)kenjis Wrote: If you really need Dependency Injection, you can install a DI container, and create controllers by the container. Thank you very much for the detailed response! This helped me a lot. (08-09-2023, 11:21 AM)ozornick Wrote: There is no DI container. Autowire is also not. I really appreciate your help |
Welcome Guest, Not a member yet? Register Sign In |