dongtui9168 2013-10-21 05:12
浏览 63
已采纳

使用一个或两个全局可以吗?

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?

  • 写回答

1条回答 默认 最新

  • douzuo0002 2013-10-21 09:58
    关注

    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?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀