Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to keep an instance of a Dependency Injection Container (PHP)

I've been using the DI concept for some time now, but now I'm starting to use a dependency injection container (DIC). Although one thing isn't clear for me.

In my DIC I keep (for example) a Config object and Request object. I understand that these objects in a request scope (The same instance is used each time you request it from this container) remain the same. But this only happens when I re-use the same instance of the DIC.

How should I pass the DIC arround my classes? Say that I want to use it in my Router class, do I need to pass it in the constructor of my Router class? But the Router class is created in another class, and that one should also already have this DIC object.

Or should I create a singleton of this DIC?

like image 924
jayv Avatar asked Feb 16 '12 21:02

jayv


1 Answers

Don't go the Singleton route. It effectively takes all the advantages the DIC gives you. Usually you pass the container in constructor, or as a method parameter where applicable.

Yes, this requires you to put an extra effort in passing the container object around your application, but as a result your code reflects well that these classes are dependent on this object to work.

like image 69
Mchl Avatar answered Sep 28 '22 09:09

Mchl