Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lazy load with Dependency Injection Container?

I am new to Dependency Injection Containers and the like.

What I have is a User object that I would like to build with a container. The user, in my case, might have tons of Comment objects associated with him/her, but I won't need them on every request.

Before, I would have had the User model create and load the Comment models itself, but I realize that is a bad practice.

If I don't want to load all the Comment upon building the User (eg - if I'd like to lazily load the comments), how do I achieve this with DI and DIC?

NOTE: I know there are solutions built, but I don't want to use them until I understand how they work. This is a theoretical question to learn the basics, and then I will most likely switch to an established framework.

like image 388
johnnietheblack Avatar asked Feb 03 '26 08:02

johnnietheblack


1 Answers

I don't think that loading dependencies in your Models is the responsibility of the Dependency Injection container. This is the job of an ORM, Data Access Objects or your application services. The DI container then is responsible for configuring and instantiating the ORM, DAO or services classes.

like image 198
Daff Avatar answered Feb 05 '26 20:02

Daff