Welcome Guest, Not a member yet? Register   Sign In
Model Dependency Injection in CodeIgniter Controller - How to Achieve It?
#1

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.
Reply
#2

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
Simple CI 4 project for beginners codeigniter-expenses
Reply
#3

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
Reply
#4

(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.
Reply
#5

(This post was last modified: 08-09-2023, 06:17 PM by tarcisiodev1.)

(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.
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

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.
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

I really appreciate your help
Reply




Theme © iAndrew 2016 - Forum software by © MyBB