简体   繁体   中英

Is It OK to Use One or Two Globals?

I'm working on a website coded in PHP and have been reading about Dependency Injection . However, I don't understand the reasoning against this kind of situation:

I have a script that currently has 2 global variables (one that's a DB connection, and one that stores the current user's data that's pulled from the DB). These 2 global variables are each used in all but one or two of my classes. The thought of implementing these global objects with DI sounds like a lot of extra typing for no real reward; up to 2 extra arguments to be passed to most of my classes along with up to 2 extra attributes to hold these injected dependencies.

I'm not asking this because I want an excuse to not have to redo the globals, I'm asking this because I really want to know:

If a small amount of objects are used by almost every object in your script, is it OK to make those objects global? What would be the benefit of using DI over globals in this case?

To answer your title: Is It OK to Use One or Two Globals? , I'd answer No . if you want to use DI, it is possible to use it everywhere. The difficulties you meet are normal, but you can overcome them.

Switching from global variables (or Singletons) to DI requires to rethink your application's architecture.

Before, you had a global $db variable, and many classes using it.

If you simply use dependency injection and inject $db into everything, that's a lot of work.

I'd recommend you to use a container , whose job will be to build your objects so that they have their dependencies injected (and that you don't have to do it yourself everywhere).

But then the next "evolution" is that you should get all your objects from the container (so that they have all their dependencies injected).

Now the question is: is it worth it? I'll let you judge, DI helps you build "better" applications (more maintenable, testable, …), is it something you are after?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM